Class: EventTimer

Inherits:
AsyncEmitter
  • Object
show all
Defined in:
lib/event_timer.rb

Overview

An event timer with second granularity. It inherits from AsyncEmitter and events are captured using the AsyncEmitter methods on and once.

Example

require 'event_timer'

timer = EventTimer.new 4

timer.on :one, lambda { |data| puts "#{data}" }
timer.on :two, lambda { |data| puts "#{data}" }
timer.on :three, lambda { |data| puts "#{data}" }
timer.on :four, lambda { |data| puts "#{data}" }

timer.start :one, 1, 1
timer.start :two, 2, 2
timer.start :three, 3, 3
timer.start :four, 4, 4
timer.cancel :four

gets

Author:

  • Greg Martin

Instance Method Summary collapse

Constructor Details

#initialize(num_timers) ⇒ EventTimer

constructor - prepares a ReadyPool for the timers. Timers can be added as needed bu it is more efficient to add them in the constructor

Parameters:

  • num_timers (FixedNum)

    the number of timers expected


35
36
37
38
39
# File 'lib/event_timer.rb', line 35

def initialize (num_timers)
	super()
	@pool = ReadyPool.new num_timers, lambda { |args| timer_proc args }
	@th_args = {}
end

Instance Method Details

#cancel(event) ⇒ Object

Cancel an event

Parameters:

  • event (Object)

    the emitter event - and valid hash key


67
68
69
70
71
# File 'lib/event_timer.rb', line 67

def cancel (event)
	@th_args[event][:mutex].synchronize do
		@th_args[event][:cancel] = true
	end
end

#start(event, time, data) ⇒ Object

Start a timer running

Parameters:

  • event (Object)

    the emitter event - and valid hash key

  • time (FixedNum)

    the number pf seconds until the event

  • data (Object)

    data passed to the timer function


48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/event_timer.rb', line 48

def start (event, time, data)
	args = {
		:event => event,
		:time => time,
		:data => data,
		:cancel => false,
		:mutex => Mutex.new
	}

	@th_args[args[:event]] = args
		
	@pool.start args
end