DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Garry has posted 5 posts at DZone. View Full User Profile

Daemonize A Ruby Process

12.08.2006
| 12439 views |
  • submit to reddit
        Here's a neat thing I found. I needed a small bit of Ruby code to run continuously in the background, but because of how Capistrano can't seem to work well with "nohup" and "&" (background job), my ruby script itself needed to be able to fork and detach from the terminal. Here's how you do it:

#!/usr/bin/ruby

pid = fork do
  loop do

    // Some code

    sleep 1.minute
  end
end

Process.detach(pid)

In my case, I just needed some code to run each minute, but it is part of a Rails app, so I didn't just want to start it with cron every minute (Rails loading is expensive). Neat eh?