Shutdown hook for Rails

后端 未结 3 1286
时光说笑
时光说笑 2021-01-08 00:35

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 ca

相关标签:
3条回答
  • 2021-01-08 00:49

    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?
    
    0 讨论(0)
  • 2021-01-08 00:57

    Be aware that you must not use Signal.trap because it does redefine what was set. There is a trick to call previous trap:

    $prev_trap = Signal.trap("TERM") do
      $prev_trap&.call
      graceful_shutdown
    end
    

    However Rails initializators are executed before app server starts, e.g. Puma redefines most of the signal traps throwing away what was defined. Therefore do not use this, it might work maybe for webrick but not in production environmentální.

    So the only reasonable option is what was already recommended by folks: at_exit in an initializer.

    0 讨论(0)
  • 2021-01-08 01:06

    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...
    $ 
    
    0 讨论(0)
提交回复
热议问题