Object
A helper that starts EventMachine reactor the optimal way depending on what Web server (if any) you are running. It should not be considered a 100% safe, general purpose EventMachine reactor “on/off switch” but is very useful in Web applications and some stand-alone applications.
This helper was inspired by Qusion project by Dan DeLeo.
h2. Key methods
{EventLoopHelper.run}
{EventLoopHelper.server_type}
# File lib/amqp/utilities/event_loop_helper.rb, line 23 23: def self.eventmachine_thread 24: @eventmachine_thread 25: end
# File lib/amqp/utilities/event_loop_helper.rb, line 27 27: def self.reactor_running? 28: EventMachine.reactor_running? 29: end
A helper that detects what app server (if any) is running and starts EventMachine reactor in the most optimal way. For event-driven servers like Thin and Goliath, this means relying on them starting the reactor but delaying execution of a block you pass to {EventLoopHelper.run} until reactor is actually running.
For Unicorn, Passenger, Mongrel and other servers and standalone apps EventMachine is started in a separate thread.
@example Using EventLoopHelper.run to start EventMachine reactor the optimal way without blocking current thread
AMQP::Utilities::EventLoopHelper.run do # Sets up default connection, accessible via AMQP.connection, and opens a channel # accessible via AMQP.channel for convenience AMQP.start exchange = AMQP.channel.fanout("amq.fanout") AMQP.channel.queue("", :auto_delete => true, :exclusive => true).bind(exchange) AMQP::channel.default_exchange.publish("Started!", :routing_key => AMQP::State.queue.name) end
@return [Thread] A thread EventMachine event loop will be started in (there is no guarantee it is already running).
@note This method, unlike EventMachine.run, DOES NOT block current thread.
# File lib/amqp/utilities/event_loop_helper.rb, line 63 63: def self.run(&block) 64: if reactor_running? 65: EventMachine.run(&block) 66: 67: return 68: end 69: 70: @eventmachine_thread ||= begin 71: case self.server_type 72: when :thin, :goliath, :evented_mongrel then 73: EventMachine.next_tick { block.call } 74: Thread.current 75: when :unicorn, :passenger, :mongrel, :scgi, :webrick, nil then 76: t = Thread.new { EventMachine.run(&block) } 77: # give EventMachine reactor some time to start 78: sleep(0.25) 79: 80: t 81: else 82: t = Thread.new { EventMachine.run(&block) } 83: # give EventMachine reactor some time to start 84: sleep(0.25) 85: 86: t 87: end 88: end 89: 90: @eventmachine_thread 91: end
Disabled; run with --debug to generate this.
Generated with the Darkfish Rdoc Generator 1.1.6.