感谢您在问题中提供的解决方案(以及激发它的答案:-)),它对我有用,即使有多个工人(Rails 3.2.9,Ruby 1.9.3p327)。
例如,在对 lib 进行一些更改后,我可能会忘记重新启动 delay_job,这让我很担心,导致我在意识到这一点之前调试了几个小时。
我将以下内容添加到我的script/rails
文件中,以允许问题中提供的代码在我们每次启动 rails 时执行,但不是每次工作人员启动时执行:
puts "cleaning up delayed job pid..."
dj_pid_path = File.expand_path('../../tmp/pids/delayed_job.pid', __FILE__)
begin
File.delete(dj_pid_path)
rescue Errno::ENOENT # file does not exist
end
puts "delayed_job ready."
不过,我面临的一个小缺点是它也会被调用rails generate
。我没有花太多时间为此寻找解决方案,但欢迎提出建议:-)
请注意,如果您使用的是独角兽,您可能希望在调用config/unicorn.rb
之前添加相同的代码。before_fork
-- 已编辑:
在对上述解决方案进行了更多尝试之后,我最终执行了以下操作:
我创建了一个script/start_delayed_job.rb
包含以下内容的文件:
puts "cleaning up delayed job pid..."
dj_pid_path = File.expand_path('../../tmp/pids/delayed_job.pid', __FILE__)
def kill_delayed(path)
begin
pid = File.read(path).strip
Process.kill(0, pid.to_i)
false
rescue
true
end
end
kill_delayed(dj_pid_path)
begin
File.delete(dj_pid_path)
rescue Errno::ENOENT # file does not exist
end
# spawn delayed
env = ARGV[1]
puts "spawing delayed job in the same env: #{env}"
# edited, next line has been replaced with the following on in order to ensure delayed job is running in the same environment as the one that spawned it
#Process.spawn("ruby script/delayed_job start")
system({ "RAILS_ENV" => env}, "ruby script/delayed_job start")
puts "delayed_job ready."
现在我可以在任何我想要的地方使用这个文件,包括“script/rails”和“config/unicorn.rb”,方法是:
# in top of script/rails
START_DELAYED_PATH = File.expand_path('../start_delayed_job', __FILE__)
require "#{START_DELAYED_PATH}"
# in config/unicorn.rb, before before_fork, different expand_path
START_DELAYED_PATH = File.expand_path('../../script/start_delayed_job', __FILE__)
require "#{START_DELAYED_PATH}"