Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Build a ruby daemon that integrates my rails environment

I need to build a ruby daemon that will use the freeswitcher eventmachine library for freeswitch.

Since few days I as looking the web for the best solution to build a ruby daemon that will integrate my rails environment, specailly my active record models. I've take a look to the excellent Ryan Bates screencast (episodes 129 custom daemon) but I'm not sure that is still an actual solution.

How do I do that in a good way?

like image 877
jjmartres Avatar asked Apr 16 '10 14:04

jjmartres


1 Answers

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!

like image 124
Logan Koester Avatar answered Oct 05 '22 13:10

Logan Koester