Class: ServiceSkeleton::HurriableTimer

Inherits:
Object
  • Object
show all
Defined in:
lib/service_skeleton/hurriable_timer.rb

Overview

A mechanism for waiting until a timer expires or until another thread signals readiness.

Instance Method Summary collapse

Constructor Details

#initialize(timeout) ⇒ HurriableTimer

Returns a new instance of HurriableTimer.



6
7
8
9
10
11
# File 'lib/service_skeleton/hurriable_timer.rb', line 6

def initialize(timeout)
  @mutex = Mutex.new
  @condition = ConditionVariable.new
  @end_time = now + timeout
  @hurried = false
end

Instance Method Details

#expired?Boolean

Returns:

  • (Boolean)


51
52
53
# File 'lib/service_skeleton/hurriable_timer.rb', line 51

def expired?
  @hurried || @end_time - now < 0
end

#hurry!Object

Cause the timer to trigger early if it hasn't already expired

This method is idempotent



42
43
44
45
46
47
48
49
# File 'lib/service_skeleton/hurriable_timer.rb', line 42

def hurry!
  @mutex.synchronize {
    @hurried = true
    @condition.broadcast
  }

  nil
end

#wait(t = nil) ⇒ Object

Wait for the timer to elapse

Any number of threads can wait on the same HurriableTimer



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/service_skeleton/hurriable_timer.rb', line 16

def wait(t = nil)
  end_time =
    if t
      [@end_time, now + t].min
    else
      @end_time
    end

  @mutex.synchronize {
    while true
      remaining = end_time - now

      if remaining < 0 || @hurried
        break
      else
        @condition.wait(@mutex, remaining)
      end
    end
  }

  nil
end