Scheduling tasks in Rails with Cron jobs & using the “Whenever” Gem.
By: Piyush Duragkar Category: Ruby on Rails Technologies: Ruby on Rails
What is a Cron job?
A job scheduler, cron lets the user execute recurring tasks at a fixed time interval. Cron jobs can run in a background process.
For eg: every minute, hour, day, or year.
Understanding the use of the ‘whenever’ gem?
The “Whenever” gem is used to add and schedule a task to the crontab file. It is a Ruby gem that gives a clear syntax for writing and deploying cron jobs.
Steps to generating Excel sheet every 12 hours.
Step 1: Add the gem ‘whenever’ to your gemfile.
Step 2: To install ‘whenever’, run the command “gem install whenever”
Step 3: Run “bundle install”
Step 4: Run “wheneverize”.
This command will generate “schedule.rb” in config.
Step 5: Create the Rake task — This will generate inside ”lib/asstes/tasks”
syntax: rails g task <namespace> <taskname>
for eg: rails g task compositions generate_excel g
Step 6: Run the task
syntax: rake <namespace>:<taskname>
for example: rake compositions:generated_excel
Step 7: Copy the task in the schedule.rb file
Step 8: The user can store the generated file in a specific folder of the application.
Step 9: Update the crontab file according to the environment.
whenever — update-crontab — set environment=’development’.
Step 10: Run “rails s”
A time-based scheduling utility, Cron jobs are used to execute commands. They are used to manage tasks in Rails. The user can use this command whenever a task is to be completed automatically and at times when the user does not have the time to enter a command manually. The user can also use it for their daily backup.