Introduction About the Cron Job
Hi Everyone!. In this post, I want to share with you a little guide that will show you how to use cron jobs in a Ruby on Rails application.
What’s a Cron Job?
A cron job is a process that is scheduled to run at a certain time (every minute, day, week, or month). On Unix systems, we can run and manage these types of processes using the cron tool. The info of the process that will run the cron tool is stored in a file called crontab.
Examples of the use of cron jobs are the following:
Generate reports. e.g, a report of daily payments from an e-commerce application.
Send reminders to users. e.g, send offer reminders from an e-commerce application.
Step 1:Install whenever gem ( https://github.com/javan/whenever )
# Cronjobs
gem 'whenever', require: false
Step 2:Go to the project and run this
cd /my-great-project
bundle exec wheneverize .
add log file path in the schedule.rb
# schedule.rb
set :output, {:error => “log/cron_error_log.log”, :standard => “log/cron_log.log”}
Step 3: Create a rake task
touch lib/tasks/first_sample_task.rake
On our task, we will simply print a message.
# lib/tasks/first_sample_task.rake
desc 'First Whenever rake task'
task first_sample_task: :environment do
Rails.logger.info "First Sample Task"
end
To see the rake tasks of our Rails application, we can use the following command.
# See all tasks
bundle exec rake --tasks
Step 4: Add in the schedule file
The structure of a cron job is the following
.--------------- minute (0-59)
| .------------ hour (0-23)
| | .--------- day of month (1-31)
| | | .------ month (1-12)
| | | | .--- day of week (0-6) (sunday=0 or 7)
| | | | |
* * * * * command to execute
An example of how to define a cron job to execute every 15minutes
# schedule.rb
every '*/15 * * * *' do
rake 'first_sample_task'
end
For Reference
https://crontab.guru/#/15_*_
Step 5:Update crontab
whenever --update-crontab
# crontab file
*/5 * * * * /bin/bash -l -c 'cd OUR_PROJECT_PATH && RAILS_ENV=production bundle exec rake first_sample_task - silent >> log/cron_log.log 2>> log/cron_error_log.log'
If we see in our logs, we can see the following.
# log/cron_log.log
I, [2022-05-04T18:05:02.890007 #98613] INFO -- : First Sample Task
I, [2022-05-04T18:20:02.944687 #98649] INFO -- : First Sample Task
Step 6: Crontab important commands
# get crontab list
crontab -l
# delete all crontab
crontab -r
# edit crontab
crontab -e
Step 7:For deployment need to import whenever file in capfile and deploy.rb
# capfile
require 'whenever/capistrano'
# deploy.rb
require 'whenever'
require 'whenever/capistrano'
If this guide has been helpful to you and your team please share it with others!
Top comments (0)