Simon Engledew's Blog

Eldritch nomenclature, conjoured for arcane contraptions to execute unerringly.

February 3, 2010 at 10:11am
home

Running Resque / Rake Tasks with Monit

script/consumer:

#!/usr/bin/env ruby

def pidfile
  @pidfile ||= File.expand_path(File.join('..', '..', 'tmp', 'pids', 'consumer.pid'),  __FILE__)
end

case ARGV.first
  when 'start' then
    require 'rubygems'
    require 'rake'
    
    ENV['QUEUE'] ||= '*'
    ENV['RAILS_ENV'] ||= 'production'

    load(File.expand_path(File.join('..', '..', 'Rakefile'),  __FILE__))

    Process.detach(consumer = Process.fork do
      begin
        Rake::Task['environment'].invoke
        Rake::Task['resque:work'].invoke
      rescue Exception => e
        $stdout.puts([e, *e.backtrace].join($/))
      end
    end)

    %x(echo "#{consumer}" > #{pidfile})

  when 'stop' then
    %x(kill `cat #{pidfile}`)
    %x(rm #{pidfile})
    
  else
    
    puts 'usage: script/consumer start|stop'
end