Skip to content

Instantly share code, notes, and snippets.

@joshuasiler
Created November 4, 2011 02:42
  • Star 8 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save joshuasiler/1338545 to your computer and use it in GitHub Desktop.
Initializer that allows EventMachine to run within Rails, and work with AMQP, Passenger, Thin and Capybara
require 'amqp'
module HiringThingEM
def self.start
if defined?(PhusionPassenger)
PhusionPassenger.on_event(:starting_worker_process) do |forked|
# for passenger, we need to avoid orphaned threads
if forked && EM.reactor_running?
EM.stop
end
Thread.new {
EM.run do
AMQP.channel ||= AMQP::Channel.new(AMQP.connect(:host=> Q_SERVER, :user=> Q_USER, :pass => Q_PASS, :vhost => Q_VHOST ))
end
}
die_gracefully_on_signal
end
else
# faciliates debugging
Thread.abort_on_exception = true
# just spawn a thread and start it up
Thread.new {
EM.run do
AMQP.channel ||= AMQP::Channel.new(AMQP.connect(:host=> Q_SERVER, :user=> Q_USER, :pass => Q_PASS, :vhost => Q_VHOST ))
end
} unless defined?(Thin)
# Thin is built on EventMachine, doesn't need this thread
end
end
def self.die_gracefully_on_signal
Signal.trap("INT") { EM.stop }
Signal.trap("TERM") { EM.stop }
end
end
HiringThingEM.start
@marianposaceanu
Copy link

Any idea how this would work with Unicorn ?

@joshuasiler
Copy link
Author

I think it works similarly to Passenger, but I'm not sure. If you get it working, I would love a contribution to the Momentarily gem (https://github.com/eatenbyagrue/momentarily) which puts the code above into a gem for easily adding to any Rails project.

@rubinix
Copy link

rubinix commented Sep 17, 2012

I'm curious if this has been verified with Passenger+Apache. Under what circumstances does the signal get trapped and handled with the callback specified in the gist? I ask because when I run this from what I can tell, Passenger traps the signal and calls it's own handler, while my handler never executes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment