在没有Rails环境的情况下加载Resque工作进程?

4

我有一些与Rails无关的Resque作业,但我很难在没有Rails环境的情况下启动工作进程。我看过这篇文章,但并没有什么帮助 (ruby resque without loading rails environment)

以下是我的当前rake文件:

require "resque/tasks"

task "resque:setup" do
  root_path = "#{File.dirname(__FILE__)}/../.."

  require "#{root_path}/app/workers/myworker.rb"
end

#task "resque:setup" => :environment

被注释的任务会加载Rails环境,一切都可以正常运行,但这不是我想要的。当运行rake resque:work时,我收到了以下错误信息:

rake aborted!
No such file to load -- application_controller

Tasks: TOP => resque:work => resque:preload
2个回答

6

如果你只添加了一个lib/tasks/resque.rake文件,而没有修改你的Rakefile,那么当你调用rake resque:work时,你仍然会加载你的Rails环境。尝试使用以下Rakefile:

unless ENV['RESQUE_WORKER'] == 'true'
  require File.expand_path('../config/application', __FILE__)
  My::Application.load_tasks 
else
  ROOT_PATH = File.expand_path("..", __FILE__)
  load File.join(ROOT_PATH, 'lib/tasks/resque.rake')
end

然后在你的resque.rake文件中添加以下内容:

require "resque/tasks"

task "resque:setup" do
  raise "Please set your RESQUE_WORKER variable to true" unless ENV['RESQUE_WORKER'] == "true"
  root_path = "#{File.dirname(__FILE__)}/../.."
  require "#{root_path}/app/workers/myworker.rb"
end

然后调用rake resque:work RESQUE_WORKER=true

-2

我参考了链接这里,这个方法对我来说完全有效:

通过运行,解决了这个错误。

$> QUEUE=* rake environment resque:work

一个更简洁的解决方案是定义一个Rake任务:
task "resque:setup" => :environment do
  ENV['QUEUE'] ||= '*'
  #for redistogo on heroku https://dev59.com/zXE85IYBdhLWcg3wyGp_
  Resque.before_fork = Proc.new { ActiveRecord::Base.establish_connection }
end

现在

rake resque:work

完美运行

谢谢。


2
这可以确保Rails环境已经加载。OP询问如何在没有Rails的情况下运行它。 - jwadsack

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接