tiny_daemon -- An easy way to daemonize your Rake task

2 Jan 2014

I have researched about how to daemonize my Rake task and how I can use it in my deployment script.

I need a background task that is running all the time (not a cron job) and it should be restarted when I deploy a new code to the server.

The gem daemons seems to be the most popular choice. But the gem has its weirdness:

  1. No idea where the source code is hosted
  2. The gem is too big for my use case (~10 files)
  3. It seems to use the old way of daemonizing (Hint: we can use Process.daemon() now)
  4. It doesn't have test cases (Why????)

With all those reasons (and I want to learn about this thing), I've decided to build my own gem.

Here it is: Github's repo, or you can use it with `gem 'tiny_daemon'`.

It can just daemonize any Ruby code block. It also tracks the process and make sure that you have only one process per one app_name.

For example, you can write your Rake task like this:

namespace :daemon do task :start => :environment do is_running = true d = TinyDaemon.new("some_task", "tmp/pids", "log") d.stop # Make sure we stop before start a new process d.exit { is_running = false } d.start do while is_running puts "Test" sleep(0.1) end end end task :stop => :environment do TinyDaemon.new("some_task", "tmp/pids", "log").stop end end

Check it out!