####################################################################
# Simple queue daemon example
# Using synchronous Beanstalk Ruby driver (beanstalk-client)
####################################################################
$:.unshift ::File.dirname(__FILE__) + '/../lib'

require 'rubygems'
require 'raemon'
require 'beanstalk-client'

class JobWorker
  include Raemon::Worker
  
  def start
    super
    @beanstalk = Beanstalk::Pool.new(['localhost:11300'])
  end
  
  def stop
    super
    @beanstalk.close
  end
  
  def run
    loop do
      begin
        job = @beanstalk.reserve(2)
      rescue Beanstalk::TimedOut
      end
      
      if job
        logger.info "(#{Process.ppid}:#{Process.pid}) got job: #{job.inspect}"
        
        # process job here ...
        job.delete
      end
      
      heartbeat!
    end
  end
end

ROOT_DIR = File.expand_path('~')

# Raemon::Master.start 3, JobWorker, {
#   :detach   => true,
#   :logger   => Logger.new("#{ROOT_DIR}/beanstalk.log"),
#   :pid_file => "#{ROOT_DIR}/beanstalk.pid"
# }

Raemon::Master.start 3, JobWorker
