I build daemons for my rails environments all the time. The daemons gem really takes all the work out of it. Here's a little template extracted from my latest rails app (script/yourdaemon), as an example. I use the eventmachine gem, but the idea is the same:
#!/usr/bin/env ruby
require 'rubygems'
require 'daemons'
class YourDaemon
def initialize
end
def dostuff
logger.info "About to do stuff..."
EventMachine::run {
# Your code here
}
end
def logger
@@logger ||= ActiveSupport::BufferedLogger.new("#{RAILS_ROOT}/log/your_daemon.log")
end
end
dir = File.expand_path(File.join(File.dirname(__FILE__), '..'))
daemon_options = {
:multiple => false,
:dir_mode => :normal,
:dir => File.join(dir, 'tmp', 'pids'),
:backtrace => true
}
Daemons.run_proc('your_daemon', daemon_options) do
if ARGV.include?('--')
ARGV.slice! 0..ARGV.index('--')
else
ARGV.clear
end
Dir.chdir dir
require File.expand_path(File.join(File.dirname(__FILE__), '..', 'config', 'environment'))
YourDaemon.new.dostuff
end
This gives you all the usual script/yourdaemon [run|start|stop|restart], and you can pass arguments into the daemon after a "--". In production you'll want to use god or monit to make sure the daemon gets restarted if it dies. Have fun!