class Timers
An efficient sorted set of timers.
Nested
Definitions
def initialize
Initialize the timers.
Implementation
def initialize
@heap = PriorityHeap.new
@scheduled = []
end
def size
Signature
-
returns
Integer
The number of timers in the heap.
Implementation
def size
flush!
return @heap.size
end
def schedule(time, block)
Schedule a block to be called at a specific time in the future.
Signature
-
parameter
time
Float
The time at which the block should be called, relative to
#now
.-
parameter
block
Proc
The block to call.
Implementation
def schedule(time, block)
handle = Handle.new(time, block)
@scheduled << handle
return handle
end
def after(offset, &block)
Schedule a block to be called after a specific time offset, relative to the current time as returned by #now
.
Signature
-
parameter
offset
#to_f
The time offset from the current time at which the block should be called.
-
yields
{|now| ...}
When the timer fires.
Implementation
def after(offset, &block)
schedule(self.now + offset.to_f, block)
end
def wait_interval(now = self.now)
Compute the time interval until the next timer fires.
Signature
-
parameter
now
Float
The current time.
-
returns
Float | Nil
The time interval until the next timer fires, if any.
Implementation
def wait_interval(now = self.now)
flush!
while handle = @heap.peek
if handle.cancelled?
@heap.pop
else
return handle.time - now
end
end
end
def now
Signature
-
returns
Float
The current time.
Implementation
def now
::Process.clock_gettime(::Process::CLOCK_MONOTONIC)
end
def fire(now = self.now)
Fire all timers that are ready to fire.
Signature
-
parameter
now
Float
The current time.
Implementation
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