Share This Article
In this article will show you how to implement cron jobs in Rails. A cron job is a type of job or task executed at a particular time or interval.
This can be very useful if you want to automate certain tasks like sending emails, backing up databases, etc.
Rails come with a gem named whenever, making it very easy to create and manage cron jobs.
In this article, we’ll see how to create a cron job using the whenever gem.
1. Install the whenever gem
gem install whenever
2. Generate the configuration file
wheneverize .
This will generate a file named config/schedule.rb
in your project.
3. Edit the configuration file
Open the config/schedule.rb
file and edit it as you need.
Here’s an example:
Every 1.day, at: "5:00 pm" do
rake "send_reminders"
end
Every 1.day, at: "6:00 pm" do
rake "cleanup"
end
4. Update the crontab
whenever --update-crontab
This will update the crontab with the jobs you defined in the configuration file.
You can also use the --set enviroment=development
option to edit the development crontab or the --set enviroment=production
option to update the production crontab.
5. Check the crontab
You can check the current crontab using the crontab -l
command.
$ crontab -l
# Begin Whenever generated tasks for: /Users/jorge/Desktop/blog/config/schedule.rb
0 23 * * * /bin/bash -l -c 'cd /Users/jorge/Desktop/blog && script/rails runner -e development '\''send_reminders'\'''
1 23 * * * /bin/bash -l -c 'cd /Users/jorge/Desktop/blog && script/rails runner -e development '\''cleanup'\'''
# End Whenever generated tasks for: /Users/jorge/Desktop/blog/config/schedule.rb
6. Remove the jobs from the crontab
To remove the jobs you defined using the whenever gem; you can use the whenever --clear-crontab
command.
This will remove all the jobs from the crontab.
You can also use the --set enviroment=development
option to remove the jobs from the development crontab or the --set enviroment=production
option to remove the jobs from the production crontab.
Finally, don’t forget to remove the config/schedule.rb
file from your project when you are done.
Summary
In this article, you’ve learned how to create rails cron jobs using the whenever gem. You’ve also known how to update, list, and clear the cron jobs.
I hope you enjoyed this article.