views:

460

answers:

1

Hi there,

We have to use delayed_job (or some other background-job processor) to run jobs in the background, but we're not allowed to change the boot scripts/boot-levels on the server. This means that the daemon is not guaranteed to remain available if the provider restarts the server (since the daemon would have been started by a capistrano recipe that is only run once per deployment).

Currently, the best way I can think of to ensure the delayed_job daemon is always running, is to add an initializer to our Rails application that checks if the daemon is running. If it's not running, then the initializer starts the daemon, otherwise, it just leaves it be.

The question, therefore, is how do we detect that the Delayed_Job daemon is running from inside a script? (We should be able to start up a daemon fairly easily, bit I don't know how to detect if one is already active).

Anyone have any ideas?

Regards, Bernie

Based on the answer below, this is what I came up with. Just put it in config/initializers and you're all set:

#config/initializers/delayed_job.rb

DELAYED_JOB_PID_PATH = "#{Rails.root}/tmp/pids/delayed_job.pid"

def start_delayed_job
  Thread.new do 
    `ruby script/delayed_job start`
  end
end

def process_is_dead?
  begin
    pid = File.read(DELAYED_JOB_PID_PATH).strip
    Process.kill(0, pid.to_i)
    false
  rescue
    true
  end
end

if !File.exist?(DELAYED_JOB_PID_PATH) && process_is_dead?
  start_delayed_job
end
+2  A: 

Check for the existence of the daemons PID file (File.exist? ...). If it's there then assume it's running else start it up.

Tony Fontenot
Great! Sounds easy! Would you happen to where I can find that file?
btelles
You will find the file in the tmp/pids folder of your app. You might also want to check whether a process with the ID from the file exists. The PID file might still exist after a crash.
Tomas Markauskas
Excellent! Thanks! I'll upvote for now, and wait to see if there are any other alternatives for a day or 2.
btelles
You have to look for the PID file *and* if an entry exists in the process table with that ID, *AND* probably also check to see that it has the right name. It's very possible for the first two tests to be true without the process at that ID being the one that is expected if the system went down unexpectedly leaving a stale PID file. Perhaps a faster way to test is to have the daemon process respond to some sort of heartbeat request. Send the request and if you get the right response you know the code you need is running. In that case the PID file test is not really needed.
Greg