fix process#alive? to not raise on no such file
[god.git] / lib / god / timer.rb
blob5f1fd9209ff11326db52662f6af1b77c1bcfac83
1 module God
2   
3   class TimerEvent
4     attr_accessor :condition, :at
5     
6     def initialize(condition, interval)
7       self.condition = condition
8       self.at = Time.now.to_i + interval
9     end
10   end
11   
12   class Timer
13     INTERVAL = 0.25
14     
15     attr_reader :events, :timer
16     
17     @@timer = nil
18     
19     def self.get
20       @@timer ||= Timer.new
21     end
22     
23     def self.reset
24       @@timer = nil
25     end
26     
27     # Start the scheduler loop to handle events
28     def initialize
29       @events = []
30       @mutex = Mutex.new
31       
32       @timer = Thread.new do
33         loop do
34           # get the current time
35           t = Time.now.to_i
36           
37           # iterate over each event and trigger any that are due
38           @events.each do |event|
39             if t >= event.at
40               self.trigger(event)
41               @mutex.synchronize do
42                 @events.delete(event)
43               end
44             else
45               break
46             end
47           end
48           
49           # sleep until next check
50           sleep INTERVAL
51         end
52       end
53     end
54     
55     # Create and register a new TimerEvent with the given parameters
56     def schedule(condition, interval = condition.interval)
57       @mutex.synchronize do
58         @events << TimerEvent.new(condition, interval)
59         @events.sort! { |x, y| x.at <=> y.at }
60       end
61     end
62     
63     # Remove any TimerEvents for the given condition
64     def unschedule(condition)
65       @mutex.synchronize do
66         @events.reject! { |x| x.condition == condition }
67       end
68     end
69     
70     def trigger(event)
71       Hub.trigger(event.condition)
72     end
73     
74     # Join the timer thread
75     def join
76       @timer.join
77     end
78   end
79   
80 end