1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
#!/usr/bin/ruby pid = fork do Signal.trap('HUP', 'IGNORE') # Don't die upon logout loop do // Some code sleep 60 end end Process.detach(pid) |
Daemonize a Ruby process
I’m not too keen on this code. It doesn’t tie up all of the loose ends. You really need to do checks you haven’t reached the process limit, trap signals, close file descriptors, and such. I’m using one of the Daemonize libs (not sure if it’s the same one atmos mentions, as mine doesn’t have start/stop/restart but just daemonizes with a single call).
Still, depending on what sort of thing you’re doing, I’m sure it’s enough for 99% of uses. If it’s mission critical though, you need something a bit harder.
http://snippets.dzone.com/posts/show/2265 – ruby daemon module
Nothing to do with daemonizing ruby but another solution to the overall problem would be to use cron to call wget to hit a page on your rails app every 5 minutes and put the functionality in that page.
That way you don’t need any extra daemonised processes and you’re only spawning a new process for wget.
atmos,
No reason not to use daemonize lib. This example is just for education or very simple / lightweight tasks.
Peter,
The code is definitely not the tightest thing there is, but I am using it on a production site and it has run fine for a while. I’m not advocating everyone use this for daemonization, but for a super simple script, you can really beat this.

Why not use the daemonize lib? It rocks and has start/stop/restart for free. It’ll even generate pid files for you to kill.