Class: ZMQMachine::Timer

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

Overview

Used to track the specific expiration time and execution code for each timer.

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.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(timers, delay, periodical, timer_proc = nil, &blk) ⇒ Timer

delay is in milliseconds



239
240
241
242
243
244
245
# File 'lib/zm/timers.rb', line 239

def initialize timers, delay, periodical, timer_proc = nil, &blk
  @timers = timers
  @delay = delay.to_i
  @periodical = periodical
  @timer_proc = timer_proc || blk
  schedule_firing_time
end

Instance Attribute Details

#fire_timeObject (readonly)

Returns the value of attribute fire_time.



235
236
237
# File 'lib/zm/timers.rb', line 235

def fire_time
  @fire_time
end

#timer_procObject (readonly)

Returns the value of attribute timer_proc.



235
236
237
# File 'lib/zm/timers.rb', line 235

def timer_proc
  @timer_proc
end

Instance Method Details

#<=>(other) ⇒ Object



265
266
267
# File 'lib/zm/timers.rb', line 265

def <=>(other)
  self.fire_time <=> other.fire_time
end

#cancelObject

Cancels this timer from firing.



261
262
263
# File 'lib/zm/timers.rb', line 261

def cancel
  @timers.cancel self
end

#expired?(time) ⇒ Boolean

True when the timer should be fired; false otherwise.

Returns:

  • (Boolean)


271
272
273
274
# File 'lib/zm/timers.rb', line 271

def expired? time
  time ||= Timers.now
  time > @fire_time
end

#fireObject

Executes the callback.

Returns true when the timer is a one-shot; Returns false when the timer is periodical and has rescheduled itself.



253
254
255
256
257
# File 'lib/zm/timers.rb', line 253

def fire
  @timer_proc.call

  schedule_firing_time if @periodical
end

#inspectObject



290
# File 'lib/zm/timers.rb', line 290

def inspect; to_s; end

#periodical?Boolean

True when this is a periodical timer; false otherwise.

Returns:

  • (Boolean)


278
279
280
# File 'lib/zm/timers.rb', line 278

def periodical?
  @periodical
end

#rescheduleObject



282
283
284
# File 'lib/zm/timers.rb', line 282

def reschedule
  schedule_firing_time
end

#to_sObject



286
287
288
# File 'lib/zm/timers.rb', line 286

def to_s
  "[delay [#{@delay}], periodical? [#{@periodical}], fire_time [#{Time.at(@fire_time/1000)}] fire_delay_s [#{(@fire_time - Timers.now)/1000}]]"
end