Class: IO::Event::Timers
- Inherits:
-
Object
- Object
- IO::Event::Timers
- Defined in:
- lib/io/event/timers.rb
Overview
An efficient sorted set of timers.
Defined Under Namespace
Classes: Handle
Instance Method Summary collapse
-
#after(offset, &block) ⇒ Object
Schedule a block to be called after a specific time offset, relative to the current time as returned by #now.
-
#fire(now = self.now) ⇒ Object
Fire all timers that are ready to fire.
-
#initialize ⇒ Timers
constructor
Initialize the timers.
- #now ⇒ Object
-
#schedule(time, block) ⇒ Object
Schedule a block to be called at a specific time in the future.
- #size ⇒ Object
-
#wait_interval(now = self.now) ⇒ Object
Compute the time interval until the next timer fires.
Constructor Details
#initialize ⇒ Timers
Initialize the timers.
62 63 64 65 |
# File 'lib/io/event/timers.rb', line 62 def initialize @heap = PriorityHeap.new @scheduled = [] end |
Instance Method Details
#after(offset, &block) ⇒ Object
Schedule a block to be called after a specific time offset, relative to the current time as returned by #now.
90 91 92 |
# File 'lib/io/event/timers.rb', line 90 def after(offset, &block) schedule(self.now + offset.to_f, block) end |
#fire(now = self.now) ⇒ Object
Fire all timers that are ready to fire.
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 |
# File 'lib/io/event/timers.rb', line 118 def fire(now = self.now) # Flush scheduled timers into the heap: flush! # Get the earliest timer: while handle = @heap.peek if handle.cancelled? @heap.pop elsif handle.time <= now # Remove the earliest timer from the heap: @heap.pop # Call the block: handle.call(now) else break end end end |
#now ⇒ Object
111 112 113 |
# File 'lib/io/event/timers.rb', line 111 def now ::Process.clock_gettime(::Process::CLOCK_MONOTONIC) end |
#schedule(time, block) ⇒ Object
Schedule a block to be called at a specific time in the future.
78 79 80 81 82 83 84 |
# File 'lib/io/event/timers.rb', line 78 def schedule(time, block) handle = Handle.new(time, block) @scheduled << handle return handle end |
#size ⇒ Object
68 69 70 71 72 |
# File 'lib/io/event/timers.rb', line 68 def size flush! return @heap.size end |
#wait_interval(now = self.now) ⇒ Object
Compute the time interval until the next timer fires.
98 99 100 101 102 103 104 105 106 107 108 |
# File 'lib/io/event/timers.rb', line 98 def wait_interval(now = self.now) flush! while handle = @heap.peek if handle.cancelled? @heap.pop else return handle.time - now end end end |