Search code examples
ruby-on-railsrubycronwhenever

Whenever gem cronjob on a particular time based on model


I am using the whenever gem, to handle my cron jobs. I have an events and bookings rails application where I have an events and a bookings table.

I want to send out a mailer, with all the bookings for an event to the event organizer an hour or so before the event's start time. But I am not able to find a way to that with the whenever gem.

Currently, I am just sending out all mailers at 9pm, and that works perfectly, but I that doesn't serve my use case, since different event organizers require it at different times


Solution

  • There is a way to run whenever dynamically. Just add this line to the top of your schedule.rb:

    require "/home/username/appname/config/environment.rb"
    

    That allows you to use all your models class on the schedule.rb. For example:

    every 1.day, :at => (Booking.last.event_time - 1.hour).strftime('%I:%M %p') do
      ...
    end
    

    Also, you can use the environment variable to set the time too.

    Don't forget update crontab when time change:

    system 'bundle exec whenever --update-crontab'
    

    But cron uses to run schedule jobs (commands or shell scripts) periodically at fixed times. So, whenever isn't better solution for you. As iGian wrote at his comment - check this topic: delay job(sidekiq or similar) is more relevant to that job.