开发者

How to launch a thread at the start of a rails app and terminate it at stop

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.


(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


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

begin
  thread = start_thread
  rest_of_app
ensure
  thread.kill
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜