Dtach is the way

daemon ruby background worker


If you have a worker that doesn't stop (looping endlessly and waiting for some queue to have a job), you might want to have the ability to put this worker in the background for the following reasons:

  1. Closing the terminal will close your worker
  2. If you're in development, having a dedicated terminal window for this is too much of a pain.
  3. In production, you'd definitely need the option to put tasks in the background.
rake worker

Running this in the background means either building your daemonizing code in-ruby using daemons.rubyforge.org or something similar. Or is there another way?

Enter Dtach

Let's first quickly read through the help of dtach.

Usage: dtach -a <socket> <options>
       dtach -A <socket> <options> <command...>
       dtach -c <socket> <options> <command...>
       dtach -n <socket> <options> <command...>
  -a		Attach to the specified socket.
  -A		Attach to the specified socket, or create it if it
		  does not exist, running the specified command.
  -c		Create a new socket and run the specified command.
  -n		Create a new socket and run the specified command detached.

We can handle putting our rake task in the background a couple of different ways:

  1. Start normally, detach on demand
dtach -A /tmp/dtach.worker rake worker

# dtach -c doesn't actually have much difference except 
# that it always tries to create the socket.

This runs as normal, but when you want to dtach, you can hit Ctrl + \.

  1. Start it in the background right off the bat.
dtach -n /tmp/dtach.worker rake worker

This will just run it in the background as normal. Now when you want to re-attach it, just run:

dtach -a /tmp/dtach.worker

But why? Why not build daemonizing into your ruby script?

Well, I'm just a fan of really simple tools that doesn't try to overstep its responsibilities. Lately I've been moving away from rails (monolithic) and into *nix style philosophy (monk, sinatra, ohm, etc, etc).

blog comments powered by Disqus