Class: Actor::Timer

Inherits:
Object
  • Object
show all
Defined in:
lib/actor/timer.rb

Overview

Simple timer implementation

Instance Method Summary collapse

Constructor Details

#initialize(period, iterations, &block) ⇒ Timer

Create a new timer that fires every <period> seconds. The number of iterations specifies how many times the timer should fire.

  • Args:

    • period: the time, in seconds, between firing the timer.

    • iterations: the number times the timer should fire. 0 iterations

means fire infinitely



13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/actor/timer.rb', line 13

def initialize period, iterations, &block
  @pause_queue = Queue.new

  i = iterations == 0 ? 1.0 / 0.0 : iterations
  @timer_thread = Thread.new do
    (1..i).step do
      sleep unless @pause_queue.empty?
      block.call
      sleep period
    end
  end
end

Instance Method Details

#pauseObject

Pauses the timer. The currently executing iteration is finished before the time is paused



29
30
31
# File 'lib/actor/timer.rb', line 29

def pause
  @pause_queue << :paused
end

#resumeObject

Resumes the timer



35
36
37
38
# File 'lib/actor/timer.rb', line 35

def resume
  @pause_queue.clear
  @timer_thread.wakeup
end

#waitObject

Block the current thread until the timer has finished executing



42
43
44
# File 'lib/actor/timer.rb', line 42

def wait
  @timer_thread.join
end