服务器重新启动时运行

服务器重新启动时运行

本文介绍了启动或确保延迟作业在应用程序/服务器重新启动时运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们必须使用delay_job(或其他一些后台作业处理器)在后台运行作业,但是我们不允许更改服务器上的启动脚本/启动级别.这意味着,如果提供程序重新启动服务器,则不能保证该守护程序保持可用(因为该守护程序将由每次部署仅运行一次的capistrano配方启动).

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).

当前,我能想到的以确保delay_job守护程序始终运行的最佳方法是向我们的Rails应用程序添加一个初始化程序,以检查该守护程序是否正在运行.如果未运行,则初始化程序将启动守护程序,否则,它将保留它.

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.

因此,问题是,如何检测脚本中是否运行了Delayed_Job守护程序? (我们应该能够很容易地启动一个守护程序,有点不知道如何检测它是否已经处于活动状态.)

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).

有人有什么主意吗?

关于,伯尼

根据以下答案,这是我想出的.只需将其放在config/initializers中,就可以设置好:

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

推荐答案

检查守护程序PID文件(File.exist? ...)是否存在.如果存在,则假定它正在运行,否则将其启动.

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

这篇关于启动或确保延迟作业在应用程序/服务器重新启动时运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 19:55