Class: Wurk::TimerLoop

Inherits:
Object
  • Object
show all
Defined in:
lib/wurk/timer_loop.rb

Overview

Mutex/CV "tick every N seconds until told to stop" primitive shared by every leader-gated periodic component (History, Metrics::Rollup, Metrics::QueueRollup). Each of those used to hand-roll the same @mutex/@sleeper/@done dance; this is that dance, extracted once.

The host owns thread spawning (it needs its own safe_thread from Component for logger/handle_exception context) and the leader-gate check inside its tick — TimerLoop only owns the interval wait and the start/terminate signaling around it:

@timer = Wurk::TimerLoop.new(interval)
@thread ||= safe_thread('my-loop') { @timer.run { tick } }
def terminate = @timer.terminate

Instance Method Summary collapse

Constructor Details

#initialize(interval) ⇒ TimerLoop

Returns a new instance of TimerLoop.



18
19
20
21
22
23
# File 'lib/wurk/timer_loop.rb', line 18

def initialize(interval)
  @interval = interval
  @done = false
  @mutex = ::Mutex.new
  @sleeper = ::ConditionVariable.new
end

Instance Method Details

#runObject

Waits one interval, then yields repeatedly (waiting between calls) until #terminate is called. Matches the existing components' "don't tick immediately on boot" behavior.



28
29
30
31
32
33
34
# File 'lib/wurk/timer_loop.rb', line 28

def run
  wait
  until @done
    yield
    wait
  end
end

#terminateObject



36
37
38
39
40
41
# File 'lib/wurk/timer_loop.rb', line 36

def terminate
  @mutex.synchronize do
    @done = true
    @sleeper.signal
  end
end

#waitObject



43
44
45
46
47
# File 'lib/wurk/timer_loop.rb', line 43

def wait
  @mutex.synchronize do
    @sleeper.wait(@mutex, @interval) unless @done
  end
end