How do I schedule recurring jobs in Active Job (Rails 4.2)?

爱⌒轻易说出口 提交于 2019-11-27 17:06:36

问题


I found this Schedule one-time jobs in Rails but this only shows how schedule one-time. I am interested in scheduling a recurring job.

Delayed_job has this

self.delay(:run_at => 1.minute.from_now)

How do I do something like that in Rails 4.2/Active Job?


回答1:


Similar to rab3's answer, since ActiveJob has support for callbacks, I was thinking of doing something like

class MyJob < ActiveJob::Base
  after_perform do |job|
    # invoke another job at your time of choice 
    self.class.set(:wait => 10.minutes).perform_later(job.arguments.first)
  end

  def perform(the_argument)
    # do your thing
  end
end

activejob callbacks




回答2:


If you want to delay the job execution to 10 minutes later, two options:

  1. SomeJob.set(wait: 10.minutes).perform_later(record)

  2. SomeJob.new(record).enqueue(wait: 10.minutes)

Delay to a specific moment from now use wait_until.

  1. SomeJob.set(wait_until: Date.tomorrow.noon).perform_later(record)

  2. SomeJob.new(record).enqueue(wait_until: Date.tomorrow.noon)

Details please refer to http://api.rubyonrails.org/classes/ActiveJob/Base.html.

For recurring jobs, you just put SomeJob.perform_now(record) in a cronjob (whenever).

If you use Heroku, just put SomeJob.perform_now(record) in a scheduled rake task. Please read more about scheduled rake task here: Heroku scheduler.




回答3:


You can just re-enqueue the job at the end of the execution

class MyJob < ActiveJob::Base
  RUN_EVERY = 1.hour

  def perform
    # do your thing

    self.class.perform_later(wait: RUN_EVERY)
  end
end



回答4:


If you're using resque as your ActiveJob backend, you can use a combination of resque-scheduler's Scheduled Jobs and active_scheduler (https://github.com/JustinAiken/active_scheduler, which wraps the scheduled jobs to work properly with ActiveJob).



来源:https://stackoverflow.com/questions/25798013/how-do-i-schedule-recurring-jobs-in-active-job-rails-4-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!