Skip to content
tarcieri edited this page Mar 30, 2013 · 9 revisions

All Celluloid actors contain a timer subsystem which can be used to schedule timed events. This can be extremely useful for adding timeouts or other time-dependent features to your actors.

The simplest way to do this is with the Celluloid#after method:

class TimerExample
  include Celluloid
  attr_reader :fired, :timer

  def initialize
    @fired = false
    @timer = after(3) { puts "Timer fired!"; @fired = true }
  end
end

In this example, after waits 3 seconds then calls the given block, even though the call to initialize and vicariously TimerExample.new will have already returned. The call to after returns a Timers::Timer object that can be used to introspect on or cancel a pending timer object.

You can also reset timers, which is helpful in cases where you want to set an inactivity timeout:

class ResetExample
  include Celluloid
  INACTIVITY_TIMEOUT = 900 # wait 15 minutes for inactivity

  def initialize
    @timer = after(INACTIVITY_TIMEOUT) { terminate }
  end

  # Any method that does something and suspends the inactivity timeout
  def activity
    @timer.reset
  end
end

Resetting the timer turns it back to where it was originally, meaning it has to wait the full duration of its original timeout value from the time you reset it.

You may also create repeating (periodic) timers, using the Celluloid#every method.

See Also

  • timers gem: library providing the Celluloid timing system
Clone this wiki locally