revamped some tests
[god.git] / lib / god / timer.rb
blob19929ab4264a1952b0cb356b7ddd1ae345a98717
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 < Base
13     INTERVAL = 0.25
14     
15     attr_reader :events
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       
31       @timer = Thread.new do
32         loop do
33           # get the current time
34           t = Time.now.to_i
35           
36           # iterate over each event and trigger any that are due
37           @events.each do |event|
38             if t >= event.at
39               self.trigger(event)
40               @events.delete(event)
41             else
42               break
43             end
44           end
45           
46           # sleep until next check
47           sleep INTERVAL
48         end
49       end
50     end
51     
52     # Create and register a new TimerEvent with the given parameters
53     def schedule(condition, interval = condition.interval)
54       @events << TimerEvent.new(condition, interval)
55       @events.sort! { |x, y| x.at <=> y.at }
56     end
57     
58     def trigger(event)
59       Hub.trigger(event.condition)
60     end
61     
62     # Join the timer thread
63     def join
64       @timer.join
65     end
66   end
67   
68 end