Class: God::Timer
- Inherits:
-
Object
- Object
- God::Timer
- Defined in:
- lib/god/timer.rb
Constant Summary collapse
- INTERVAL =
0.25
- @@timer =
nil
Instance Attribute Summary collapse
-
#events ⇒ Object
readonly
Returns the value of attribute events.
-
#timer ⇒ Object
readonly
Returns the value of attribute timer.
Class Method Summary collapse
Instance Method Summary collapse
-
#initialize ⇒ Timer
constructor
Start the scheduler loop to handle events.
-
#join ⇒ Object
Join the timer thread.
-
#schedule(condition, interval = condition.interval) ⇒ Object
Create and register a new TimerEvent with the given parameters.
- #trigger(event) ⇒ Object
-
#unschedule(condition) ⇒ Object
Remove any TimerEvents for the given condition.
Constructor Details
#initialize ⇒ Timer
Start the scheduler loop to handle events
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
# File 'lib/god/timer.rb', line 28 def initialize @events = [] @mutex = Mutex.new @timer = Thread.new do loop do # get the current time t = Time.now.to_i # iterate over each event and trigger any that are due @events.each do |event| if t >= event.at self.trigger(event) @mutex.synchronize do @events.delete(event) end else break end end # sleep until next check sleep INTERVAL end end end |
Instance Attribute Details
#events ⇒ Object (readonly)
Returns the value of attribute events.
15 16 17 |
# File 'lib/god/timer.rb', line 15 def events @events end |
#timer ⇒ Object (readonly)
Returns the value of attribute timer.
15 16 17 |
# File 'lib/god/timer.rb', line 15 def timer @timer end |
Class Method Details
.get ⇒ Object
19 20 21 |
# File 'lib/god/timer.rb', line 19 def self.get @@timer ||= Timer.new end |
.reset ⇒ Object
23 24 25 |
# File 'lib/god/timer.rb', line 23 def self.reset @@timer = nil end |
Instance Method Details
#join ⇒ Object
Join the timer thread
75 76 77 |
# File 'lib/god/timer.rb', line 75 def join @timer.join end |
#schedule(condition, interval = condition.interval) ⇒ Object
Create and register a new TimerEvent with the given parameters
56 57 58 59 60 61 |
# File 'lib/god/timer.rb', line 56 def schedule(condition, interval = condition.interval) @mutex.synchronize do @events << TimerEvent.new(condition, interval) @events.sort! { |x, y| x.at <=> y.at } end end |
#trigger(event) ⇒ Object
70 71 72 |
# File 'lib/god/timer.rb', line 70 def trigger(event) Hub.trigger(event.condition) end |
#unschedule(condition) ⇒ Object
Remove any TimerEvents for the given condition
64 65 66 67 68 |
# File 'lib/god/timer.rb', line 64 def unschedule(condition) @mutex.synchronize do @events.reject! { |x| x.condition == condition } end end |