I'm working on a Rails 5.2 project that requires a scheduled asynchronous task to run nightly. I've been looking at the differences between using the whenever gem to trigger an ActiveJob job, and using whenever to trigger an old-style rake task (/lib/tasks/some_task.rake
) - I'm struggling to find much in the way of notable pros and/or cons either way. Taking the two basic example implementations below, what are the differences between the two strategies?
The differences that I can see, are that with ActiveJob, you get the added flexibility of selecting a queue for the job to run in, and triggering callbacks around the job, wheres with the rake task, you're limited to the single thread, and no callbacks are available.
Are there any other differences worth looking at?
ActiveJob
app/jobs/subscription_reminder_job.rb
:
class SubscriptionReminderJob < ApplicationJob
queue_as :default
def perform
Subscription.overdue.find_each do |overdue_subscription|
UserMailer.subscription_reminder(overdue_subscription.user, overdue_subscription).deliver_later
overdue_subscription.touch(:last_subscription_reminder_sent_at)
end
end
end
config/schedule.rb
:
every :day, at: '12:00am' do
runner "SubscriptionReminderJob.perform"
end
Rails Task
lib/tasks/send_subscription_reminders.rake
:
task send_subscription_reminders: :environment do
Subscription.overdue.find_each do |overdue_subscription|
UserMailer.subscription_reminder(overdue_subscription.user, overdue_subscription).deliver_later
overdue_subscription.touch(:last_subscription_reminder_sent_at)
end
end
config/schedule.rb
:
every :day, at: '12:00am' do
rake "send_subscription_reminders"
end