I have used the likes of Delayed Jobs and Sidekiq in previous apps, but for an app I am working on I had to create cron jobs based on user settings. I needed someway to iterate over the user’s settings and create the crons needed. I came across the whenever gem that makes it easy to create cron jobs. With a little tweaking I was able to create cron jobs based on a user’s setting.
Gem installation
In your Gemfile:
1
|
|
The reason we add require false is because whenever creates cron jobs outside of the rails app.
Next run the following command from the root of your app:
1
|
|
This will create a schedule.rb in the config file, this is where your logic for setting up crons will be. You can have a look at this railscasts on how to setup crons.
Requiring the rails app
In order to have access to your models inside the file, you need to require the application. This can be done with the following line.
1
|
|
This will load up the application which gives us access to our rails models. Now let’s say you have many users with different reminder settings.
1 2 3 4 5 6 7 8 |
|
reminder_frequency can contain for example: “sunday” or “weekday”
reminder_time contains the timestamp: “6:00pm”
This will create the cron jobs for every user. Running the following command will confirm that:
1
|
|
There are many different solutions out there for scheduled jobs, whenever makes it really easy with it’s syntax and simplicity. Let me know if you have any questions.