[英]How can I run a rake task from a delayed_job
I'd like to run a rake task (apn:notifications:deliver from the apn_on_rails gem) from a delayed_job. 我想从delayed_job运行一个rake任务(apn:notifications:从apn_on_rails gem传递)。 In other words, I'd like enqueue a delayed job which will call the apn:notifications:deliver rake task. 换句话说,我想将一个延迟的工作排入队列,这个工作将调用apn:notifications:提供rake任务。
I found this code http://pastie.org/157390 from http://geminstallthat.wordpress.com/2008/02/25/run-rake-tasks-with-delayedjob-dj/ . 我在http://geminstallthat.wordpress.com/2008/02/25/run-rake-tasks-with-delayedjob-dj/找到了这段代码http://pastie.org/157390 。
I added this code as DelayedRake.rb to my lib directory: 我将此代码作为DelayedRake.rb添加到我的lib目录中:
require 'rake'
require 'fileutils'
class DelayedRake
def initialize(task, options = {})
@task = task
@options = options
end
##
# Called by Delayed::Job.
def perform
FileUtils.cd RAILS_ROOT
@rake = Rake::Application.new
Rake.application = @rake
### Load all the Rake Tasks.
Dir[ "./lib/tasks/**/*.rake" ].each { |ext| load ext }
@options.stringify_keys!.each do |key, value|
ENV[key] = value
end
begin
@rake[@task].invoke
rescue => e
RAILS_DEFAULT_LOGGER.error "[ERROR]: task \"#{@task}\" failed. #{e}"
end
end
end
Everything runs fine until the delayed_job runs and it complains: 一切运行良好,直到delayed_job运行,它抱怨:
[ERROR]: task "apn:notifications:deliver" failed. [错误]:任务“apn:notifications:deliver”失败。 Don't know how to build task 'apn:notifications:deliver' 不知道如何构建任务'apn:notifications:deliver'
How do I let it know about apn_on_rails? 我如何让它知道apn_on_rails? I'd tried require 'apn_on_rails_tasks' at the top of DelayedRake which didn't do anything. 我试过在DelayedRake的顶部要求'apn_on_rails_tasks',它没有做任何事情。 I also tried changing the directory of rake tasks to ./lib/tasks/*.rake 我还尝试将rake任务目录更改为./lib/tasks/*.rake
I'm somewhat new to Ruby/Rails. 我对Ruby / Rails有些新意。 This is running on 2.3.5 on heroku. 这是在heroku上运行2.3.5。
为什么不做系统调用?
system "rake apn:notifications:deliver"
I believe it's easier if you call it as a separate process. 我相信如果你把它称为一个单独的过程会更容易。 See 5 ways to run commands from Ruby . 请参阅从Ruby运行命令的5种方法 。
def perform
`rake -f #{Rails.root.join("Rakefile")} #{@task}`
end
If you want to capture any errors, you should capture STDERR
as shown in the article. 如果要捕获任何错误,则应捕获STDERR
,如文章中所示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.