class Rufus::Scheduler::EmScheduler

A rufus-scheduler that uses an EventMachine periodic timer instead of a loop.

Public Class Methods

new(opts={}) click to toggle source
Calls superclass method Rufus::Scheduler::SchedulerCore.new
# File lib/rufus/sc/scheduler.rb, line 403
def initialize (opts={})

  raise LoadError.new(
    'EventMachine missing, "require \eventmachine\" might help'
  ) unless defined?(EM)

  super(opts)
end

Public Instance Methods

join() click to toggle source

Joins this scheduler. Will actually join it only if it started the underlying EventMachine.

# File lib/rufus/sc/scheduler.rb, line 447
def join

  @em_thread.join if @em_thread
end
start() click to toggle source
# File lib/rufus/sc/scheduler.rb, line 412
def start

  @em_thread = nil

  unless EM.reactor_running?
    @em_thread = Thread.new { EM.run }
    while (not EM.reactor_running?)
      Thread.pass
    end
  end

  #unless EM.reactor_running?
  #  t = Thread.current
  #  @em_thread = Thread.new { EM.run { t.wakeup } }
  #  Thread.stop # EM will wake us up when it's ready
  #end

  @timer = EM::PeriodicTimer.new(@frequency) { step }
end
stop(opts={}) click to toggle source

Stops the scheduler.

If the :stop_em option is passed and set to true, it will stop the EventMachine (but only if it started the EM by itself !).

# File lib/rufus/sc/scheduler.rb, line 437
def stop (opts={})

  @timer.cancel

  EM.stop if opts[:stop_em] and @em_thread
end

Protected Instance Methods

trigger_job(blocking, &block) click to toggle source

If 'blocking' is set to true, the block will get called at the 'next_tick'. Else the block will get called via 'defer' (own thread).

# File lib/rufus/sc/scheduler.rb, line 457
def trigger_job (blocking, &block)

  m = blocking ? :next_tick : :defer
    #
    # :next_tick monopolizes the EM
    # :defer executes its block in another thread

  EM.send(m) { block.call }
end