Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Whenever gem with Rails Active Job to schedule a batch email job

I'm trying to understand how to use whenever properly, or if I'm even using it for the right thing. I've created a job:

  class ScheduleSendNotificationsJob < ActiveJob::Base
  queue_as :notification_emails

  def perform(*args)
      user_ids = User.
                joins(:receipts).
                where(receipts: {is_read: false}).
                select('DISTINCT users.id').
                map(&:id)

      user_ids.each do |user_id|
          SendNotificationsJob.create(id: user_id)
          Rails.logger.info "Scheduled a job to send notifications to user #{user_id}"
        end  
    end
   end

I'd like to perform this job ever day at a set time. The job polls to see if there are any outstanding notifications, batches them, and then sends them to users so that a user can get one email with a bunch of notifications instead of a bunch of emails with one notification per email. I tried doing this with Delayed Job, but it seems it's not designed to schedule something on a recurring basis. So now I'm trying to do it with the whenever gem, but I can't seem to figure out how to set it up properly.

This is what I have in my config/schedule.rb file:

every 1.minute do
   runner ScheduleSendNotifications.create
end

When I run whenever -i in the console I get the following:

Lorenzs-MacBook-Pro:Heartbeat-pods lorenzsell$ whenever -i
config/schedule.rb:13:in `block in initialize': uninitialized constant Whenever::JobList::ScheduleSendNotifications (NameError)

What am I doing wrong here? Should I be using something else? I'm just learning ruby and rails so any help is very much appreciated. Thank you.

like image 747
Lorenz Avatar asked May 03 '15 23:05

Lorenz


1 Answers

The whenever gem takes a string as the argument to the runner function. Whenever doesn't actually load the Rails environment so it doesn't know about your ScheduleSendNotifications class.

The code below should get the crontab set up correctly to run your job.

every 1.minute do
  runner "ScheduleSendNotifications.create"
end

From your project directory run whenever -w to set up the crontab file. Run crontab -l to view the written crontab file. Every minute the system will execute your Rails runner. From there you may need to debug your ScheduleSendNotifications.create code if something isn't working.

like image 91
johnsorrentino Avatar answered Sep 21 '22 08:09

johnsorrentino