Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shutdown hook for Rails

I'd like to have some cleanup code run when Rails is shutting down - is that possible? My situation is that I have a few threads in the background (I'm using jruby and calling into java) that live for the life of the process and I need to let them know to shut themselves down

Thanks!

like image 532
Stuart Avatar asked Oct 22 '09 23:10

Stuart


2 Answers

Within the context of a Rails Application, the best place to put such a file is in config/initializers. In my app, I needed to Flush the Redis/Sidekiq queue whenever the development or test environments shut down. This works perfectly.

config/initializers/at_exit.rb

at_exit do
  begin
    puts 'Flushing Redis...'
    Redis.new.flushall
  rescue => e
    puts "There was an #{e.to_s} while flushing redis..."
  ensure
    puts 'Done Flushing Redis!'
  end
end unless Rails.env.production?
like image 45
danielricecodes Avatar answered Sep 22 '22 14:09

danielricecodes


Probably should just use the Ruby exit handler, which is a Kernel method:

$ irb
>> at_exit do
?>   puts 'bye...'
>> end
=> #<Proc:0xb79a87e4@(irb):1>
>> exit
bye...
$ 
like image 100
DigitalRoss Avatar answered Sep 18 '22 14:09

DigitalRoss