Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 809
luis.madrigal Avatar asked Sep 11 '14 22:09

luis.madrigal


People also ask

How active jobs work in Rails?

Active Job is a framework for declaring jobs and making them run on a variety of queuing backends. These jobs can be everything from regularly scheduled clean-ups, to billing charges, to mailings. Anything that can be chopped up into small units of work and run in parallel, really.

How do I enqueue a job in rails?

Enqueue jobs The different enqueuing options are the following: wait : With this, the job is enqueued after the mentioned time period. wait_until : With this, the job is enqueued after that the specified time has elapsed. queue : With this, the job is added to the specified queue.

What is background job rails?

Running Background Jobs in Ruby on Rails Containers – DevGraph. Products. SCALEARC. A SQL load balancer that enables you to dramatically scale and improve database performance without any code changes to your application or database.

What is an active job?

An active job allows you to stay moving, helping you maintain or improve your physical health during your daily responsibilities. Improved mental health: Active jobs provide your brain with added stimulation. Since many active jobs take place outdoors, you can receive more exposure to vitamin D.


2 Answers

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

like image 162
omencat Avatar answered Sep 22 '22 13:09

omencat


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.

like image 34
Juanito Fatas Avatar answered Sep 24 '22 13:09

Juanito Fatas