Method: EventMachine.add_timer

Defined in:
lib/eventmachine.rb

.add_timer(*args, &block) ⇒ Object

Adds a one-shot timer to the event loop. Call it with one or two parameters. The first parameters is a delay-time expressed in seconds (not milliseconds). The second parameter, if present, must be an object that responds to :call. If 2nd parameter is not given, then you can also simply pass a block to the method call.

This method may be called from the block passed to run or from any callback method. It schedules execution of the proc or block passed to it, after the passage of an interval of time equal to *at least* the number of seconds specified in the first parameter to the call.

add_timer is a non-blocking method. Callbacks can and will be called during the interval of time that the timer is in effect. There is no built-in limit to the number of timers that can be outstanding at any given time.

Examples:

Setting a one-shot timer with EventMachine


EventMachine.run {
  puts "Starting the run now: #{Time.now}"
  EventMachine.add_timer 5, proc { puts "Executing timer event: #{Time.now}" }
  EventMachine.add_timer(10) { puts "Executing timer event: #{Time.now}" }
}

See Also:



323
324
325
326
327
328
329
330
331
332
# File 'lib/eventmachine.rb', line 323

def self.add_timer *args, &block
  interval = args.shift
  code = args.shift || block
  if code
    # check too many timers!
    s = add_oneshot_timer((interval.to_f * 1000).to_i)
    @timers[s] = code
    s
  end
end