1

I would like to automatically launch a background thread at the start of my rails app and terminate it at stop (Ctrl + C in dev mode or kill signal in production)

I've no problem launching my thread at start, but I can't manage to terminate it at stop. Either it doesn't stop, either it prevent my rails app from quitting.

Is there an automatic way ? Or should I hook the rails stop ? How ?

Thanks in advance for your advices.

P.S. By the way, do you know how to use the "pid" feature of the rails thread ? I mean the way to put a small text file in tmp/pids at start and removing it automatically. I'm sure there are some functions to do that.

Offirmo
  • 18,962
  • 12
  • 76
  • 97

2 Answers2

2

(Old question, but I don't like unanswered questions ;-)

A convenient way to do this is to set "finalizers" similar to rails "initializers". You can then launch threads in initializers and close them in finalizers.

  1. Create a "config/finalizers" directory near the "config/initializers" directory.
  2. put this code in an initializer :

(we use ruby "at exit", cf. Shutdown hook for Rails)

at_exit do
   finalizer_files = File.join(::Rails.root.to_s, "config/finalizers/*.rb")
   Dir.glob(finalizer_files).sort.each do |finalizer_file|
      require finalizer_file
   end
end

3. Then we can use something like that in a "finalizer" : (here we attempt to stop "workers" supposedly launched in initializers)

if Settings.web_app.engine.workers_count != 0 && Settings.web_app.engine.auto_manage_workers then
   puts '    * Automatic shutdown of workers'
   ...
end
Community
  • 1
  • 1
Offirmo
  • 18,962
  • 12
  • 76
  • 97
1

Have you tried wrapping your app in a begin..ensure like this:

begin
  thread = start_thread
  rest_of_app
ensure
  thread.kill
end
mckeed
  • 9,719
  • 2
  • 37
  • 41
  • Thank you, but I feel bad about wrapping my rails app in a begin .. end. There must be a better way. – Offirmo Apr 05 '11 at 07:54