Class: IO::Event::Timers

Inherits:
Object
  • Object
show all
Defined in:
lib/io/event/timers.rb

Defined Under Namespace

Classes: Handle

Instance Method Summary collapse

Constructor Details

#initializeTimers

Returns a new instance of Timers.



41
42
43
44
# File 'lib/io/event/timers.rb', line 41

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.



64
65
66
# File 'lib/io/event/timers.rb', line 64

def after(offset, &block)
  schedule(self.now + offset.to_f, block)
end

#fire(now = self.now) ⇒ Object



84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# File 'lib/io/event/timers.rb', line 84

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

#nowObject



80
81
82
# File 'lib/io/event/timers.rb', line 80

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.



54
55
56
57
58
59
60
# File 'lib/io/event/timers.rb', line 54

def schedule(time, block)
  handle = Handle.new(time, block)
  
  @scheduled << handle
  
  return handle
end

#sizeObject



46
47
48
49
50
# File 'lib/io/event/timers.rb', line 46

def size
  flush!
  
  return @heap.size
end

#wait_interval(now = self.now) ⇒ Object



68
69
70
71
72
73
74
75
76
77
78
# File 'lib/io/event/timers.rb', line 68

def wait_interval(now = self.now)
  flush!
  
  while handle = @heap.peek
    if handle.cancelled?
      @heap.pop
    else
      return handle.time - now
    end
  end
end