Simplified config file (removing meddle construct)
[god.git] / lib / god / timer.rb
blob1ff32a41dba53af5949188971fa416655b264061
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       
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     # Remove any TimerEvents for the given condition
59     def unschedule(condition)
60       @events.reject! { |x| x.condition == condition }
61     end
62     
63     def trigger(event)
64       Hub.trigger(event.condition)
65     end
66     
67     # Join the timer thread
68     def join
69       @timer.join
70     end
71   end
72   
73 end