Devilishly Simple Background Ruby: Daemons

Picture of a paper devil

If you’re looking for a super simple way to daemonize a Ruby script then have a sneaky peek at Daemons.

This description from the site sums up what the deal is with Daemons -

Daemons provides an easy way to wrap existing ruby scripts (for example a self-written server) to be run as a daemon and to be controlled by simple start/stop/restart commands.

All you need do if you want a Ruby script to run in the background as a daemon, say my_app.rb, is to wrap a call to my_app.rb like this -

my_app_control.rb

 1 #!/usr/bin/env ruby
 2 
 3 # This is my_app_control.rb. It allows you to daemonize my_app.rb
 4 #
 5 # Usage: ruby my_app_control.rb [start|stop|restart]
 6 #
 7 
 8 require 'rubygems'
 9 require 'daemons'
10 
11 Daemons.run('my_app.rb')

If you enter this at the console -

ruby my_app_control.rb start

The script __my_app.rb__ will start in the background, and a pid file will be created containing the process id of your newly spawned task. Unfortunately, because of the way that Daemons works, it is not easy to get feedback by way of console messages with a puts or print call, but you do have the option to log output to a file.

There are some other ways in which Daemons can be utilised that are well documented on the site. Nice, neat, try it.

Permalink | comments(View)

blog comments powered by Disqus