Class: EasyTimers::Group
- Inherits:
-
Object
- Object
- EasyTimers::Group
- Defined in:
- lib/easy_timers/group.rb
Overview
Maintains a list of timers.
Constant Summary collapse
- GRANULARITY =
milliseconds
1000
Instance Method Summary collapse
-
#delete(name) ⇒ Object
Delete a timer from the group.
-
#get_current_time ⇒ Object
Return the current time in seconds.
-
#initialize ⇒ Group
constructor
Create a new instance and begin the loop.
-
#insert(timer) ⇒ Object
Insert a new timer into the group.
-
#loop ⇒ Object
Perform a single loop.
Constructor Details
#initialize ⇒ Group
Create a new instance and begin the loop
11 12 13 14 15 16 17 18 19 20 21 |
# File 'lib/easy_timers/group.rb', line 11 def initialize @events = [] # Maintained in sorted order of furthest-soonest, aka descending order. @names = Hash.new do |hash,key| # Each array in descending order. hash[key] = [] end @looping_thread = Thread.new() do while true self.loop() end end end |
Instance Method Details
#delete(name) ⇒ Object
Delete a timer from the group.
45 46 47 48 49 50 51 52 53 |
# File 'lib/easy_timers/group.rb', line 45 def delete(name) if @names[name].size() > 0 @names[name].each do |timer| timer.cancel() end @names.delete(name) @looping_thread.run() end end |
#get_current_time ⇒ Object
Return the current time in seconds
88 89 90 |
# File 'lib/easy_timers/group.rb', line 88 def get_current_time() return Time.now.gmtime.to_f end |
#insert(timer) ⇒ Object
Insert a new timer into the group
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
# File 'lib/easy_timers/group.rb', line 26 def insert(timer) index = @events.index do |element| timer.time > element.time end if index == nil @events.push(timer) else @events.insert(index, timer) end @names[timer.name].push(timer) @looping_thread.run() return timer.name end |
#loop ⇒ Object
Perform a single loop.
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
# File 'lib/easy_timers/group.rb', line 57 def loop() if @events.empty? sleep #until woken else time = self.get_current_time() while @events.last.time <= time timer = @events.pop @names[timer.name].pop if timer.cancelled? == false if timer.recurring == true newTime = timer.time + timer.interval newTimer = Timer.new(newTime, timer.name, timer.interval, timer.recurring, timer.callback) self.insert(newTimer) end Thread.new do timer.callback.call end end end untilNext = @events.last.time - time if untilNext < 0.0 untilNext = 0.0 end sleep untilNext end end |