Class: ZMQMachine::Timers

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

Overview

Manages the addition and cancellation of all timers. Each #Reactor maintains its own set of timers; the timer belongs to the reactor context.

This should never be instantiated directly by user code. A timer must be known to the #Reactor in which it is running, so use the #Reactor#oneshot_timer and #Reactor#periodical_timer convenience methods. It ensures that new timers are installed in the correct #Reactor.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(exception_handler) ⇒ Timers

Returns a new instance of Timers.



50
51
52
53
# File 'lib/zm/timers.rb', line 50

def initialize(exception_handler)
  @exception_handler = exception_handler
  @timers = []
end

Class Method Details

.nowObject

Returns the current time using the following algo:

(Time.now.to_f * 1000).to_i

Added as a class method so that it can be overridden by a user who wants to provide their own time source. For example, a user could use a third-party gem that provides a better performing time source.



206
207
208
# File 'lib/zm/timers.rb', line 206

def self.now
  (Time.now.to_f * 1000).to_i
end

.now_convertedObject

Convert Timers.now to a number usable by the Time class.



212
213
214
# File 'lib/zm/timers.rb', line 212

def self.now_converted
  now / 1000.0
end

Instance Method Details

#add_oneshot(delay, timer_proc = nil, &blk) ⇒ Object

Adds a non-periodical, one-shot timer in order of first-to-fire to last-to-fire.

Returns nil unless a timer_proc or blk are provided. There is no point to an empty timer that does nothing when fired.



66
67
68
69
70
71
72
73
# File 'lib/zm/timers.rb', line 66

def add_oneshot delay, timer_proc = nil, &blk
  blk ||= timer_proc
  return nil unless blk

  timer = Timer.new :timers => self, :delay => delay, :periodical => false, :timer_proc => blk
  add timer
  timer
end

#add_oneshot_at(exact_time, timer_proc = nil, &blk) ⇒ Object

Adds a non-periodical, one-shot timer to be fired at the specified time.



78
79
80
81
82
83
84
85
# File 'lib/zm/timers.rb', line 78

def add_oneshot_at exact_time, timer_proc = nil, &blk
  blk ||= timer_proc
  return nil unless blk

  timer = Timer.new :timers => self, :exact_time => exact_time, :periodical => false, :timer_proc => blk
  add timer
  timer
end

#add_periodical(delay, timer_proc = nil, &blk) ⇒ Object

Adds a periodical timer in order of first-to-fire to last-to-fire.

Returns nil unless a timer_proc or blk are provided. There is no point to an empty timer that does nothing when fired.



94
95
96
97
98
99
100
101
# File 'lib/zm/timers.rb', line 94

def add_periodical delay, timer_proc = nil, &blk
  blk ||= timer_proc
  return nil unless blk

  timer = Timer.new :timers => self, :delay => delay, :periodical => true, :timer_proc => blk
  add timer
  timer
end

#cancel(timer) ⇒ Object

Cancel the timer.

Returns true when cancellation succeeds. Returns false when it fails to find the given timer.



109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
# File 'lib/zm/timers.rb', line 109

def cancel timer
  i = index timer

  # when #index doesn't find a match, it returns an index 1 past
  # the end, so check for that
  if i < @timers.size && timer == @timers.at(i)
    @timers.delete_at(i) ? true : false
  else
    # slow branch; necessary since the #index operation works
    # solely from the timer.fire_time attribute. There
    # could be multiple timers scheduled to fire at the
    # same time so the equivalence test above could fail
    # on the first index returned, so fallback to this
    # slower method
    size = @timers.size
    @timers.delete_if { |t| t == timer }

    # true when the array has shrunk, false otherwise
    @timers.size != size
  end
end

#fire_expiredObject

A convenience method that loops through all known timers and fires all of the expired timers.

– Internally the list is sorted whenever a timer is added or deleted. It stops processing this list when the next timer is not yet expired; it knows all subsequent timers are not expired too.

timers should be sorted by expiration time NOTE: was using #delete_if here, but it does not delete any items when the break executes before iterating through the entire set; that’s unacceptable so I save each timer for deletion and do that in a separate loop

Additionally, some timers may execute code paths that cancel other timers. If those timers are deleted while we are still iterating over them, the behavior is undefined (each runtime can handle it differently). To avoid that issue, we determine if they are expired and save them off for final processing outside of the loop. Any firing timer that deletes another timer will be safe.



153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
# File 'lib/zm/timers.rb', line 153

def fire_expired
  # all time is expected as milliseconds
  now = Timers.now
  runnables, periodicals, expired_count = [], [], 0

  # defer firing the timer until after this loop so we can clean it up first
  @timers.each do |timer|
    break unless timer.expired?(now)
    runnables << timer
    periodicals << timer if timer.periodical?
    expired_count += 1
  end

  remove expired_count

  while timer = runnables.shift
    begin
      timer.fire
    rescue => e
      if @exception_handler
        @exception_handler.call(e)
      else
        renew(periodicals)
        raise
      end
    end
  end

  renew periodicals
end

#listObject



55
56
57
# File 'lib/zm/timers.rb', line 55

def list
  @timers
end

#rescheduleObject

Runs through all timers and asks each one to reschedule itself from Timers.now + whatever delay was originally recorded.



187
188
189
190
191
192
193
194
195
# File 'lib/zm/timers.rb', line 187

def reschedule
  timers = @timers.dup
  @timers.clear

  timers.each do |timer|
    timer.reschedule
    add timer
  end
end