开发者

Build a ruby daemon that integrates my rails environment

I ne开发者_运维问答ed 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?


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜