3 # timer event, something to do and when/how often to do it
6 # when this action is due next (updated by tick())
9 # is this action blocked? if so it won't be run
10 attr_accessor :blocked
12 # period:: how often (seconds) to run the action
13 # data:: optional data to pass to the proc
14 # once:: optional, if true, this action will be run once then removed
15 # func:: associate a block to be called to perform the action
18 def initialize(period, data=nil, once=false, &func)
27 # run the action by calling its proc
39 # timer handler, manage multiple Action objects, calling them when required.
40 # The timer must be ticked by whatever controls it, i.e. regular calls to
41 # tick() at whatever granularity suits your application's needs.
42 # Alternatively you can call run(), and the timer will tick itself, but this
43 # blocks so you gotta do it in a thread (remember ruby's threads block on
44 # syscalls so that can suck).
52 # period:: how often (seconds) to run the action
53 # data:: optional data to pass to the action's proc
54 # func:: associate a block with add() to perform the action
56 # add an action to the timer
57 def add(period, data=nil, &func)
59 @timers[@handle] = Action.new(period, data, &func)
63 # period:: how often (seconds) to run the action
64 # data:: optional data to pass to the action's proc
65 # func:: associate a block with add() to perform the action
67 # add an action to the timer which will be run just once, after +period+
68 def add_once(period, data=nil, &func)
70 @timers[@handle] = Action.new(period, data, true, &func)
74 # remove action with handle +handle+ from the timer
76 @timers.delete_at(handle)
79 # block action with handle +handle+
81 @timers[handle].blocked = true
84 # unblock action with handle +handle+
86 @timers[handle].blocked = false
89 # you can call this when you know you're idle, or you can split off a
90 # thread and call the run() method to do it for you.
93 diff = (Time.now - @lasttime).to_f
95 @timers.compact.each { |timer|
96 timer.in = timer.in - diff
98 @timers.compact.each { |timer|
103 @timers.delete(timer)
109 # don't do anything on the first tick
114 # the timer will tick() itself. this blocks, so run it in a thread, and
115 # watch out for blocking syscalls
116 def run(granularity=0.1)