Start or ensure that Delayed Job runs when an application/server restarts

前端 未结 4 590
被撕碎了的回忆
被撕碎了的回忆 2020-12-28 20:27

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 serve

4条回答
  •  甜味超标
    2020-12-28 20:49

    Some more cleanup ideas: The "begin" is not needed. You should rescue "no such process" in order not to fire new processes when something else goes wrong. Rescue "no such file or directory" as well to simplify the condition.

    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 daemon_is_running?
      pid = File.read(DELAYED_JOB_PID_PATH).strip
      Process.kill(0, pid.to_i)
      true
    rescue Errno::ENOENT, Errno::ESRCH   # file or process not found
      false
    end
    
    start_delayed_job unless daemon_is_running?
    

    Keep in mind that this code won't work if you start more than one worker. And check out the "-m" argument of script/delayed_job which spawns a monitor process along with the daemon(s).

提交回复
热议问题