How to run Cron jobs in Rails?

Better Stack Team
Updated on October 5, 2023

To run Cron jobs in a Rails application, you can use a gem called whenever. This gem allows you to define your Cron jobs in Ruby syntax and generates a crontab file for you. Here are the steps to use whenever in your Rails application:

🔭 Want to get alerted when your Cron doesn’t run correctly?

Go to Better Stack and start monitoring in 5 minutes.

Install whenever gem

Add the whenever gem to your Gemfile and run bundle install:

 
gem 'whenever', require: false

Generate configuration file

Generate the whenever configuration file. Execute this from your Rails app root to create the schedule.rb file:

 
bundle exec wheneverize .

Define your Cron jobs

Define your Cron jobs in config/schedule.rb:

 
every 1.day, at: '4:30 am' do
  runner 'MyModel.my_task'
end

This Cron job will run every day at 4:30 am and execute the my_task method on the MyModel model.

Update crontab

Let whenever write your job into the crontab.

 
bundle exec whenever --update-crontab

Note: Whenever takes into consideration your Rails app environment when updating the crontab. If you're using the development environment, then run the command with the option below (default is production).

 
whenever --update-crontab --set environment='development'

This will update the crontab file with your Cron jobs. You can verify that the Cron jobs have been added to the crontab file by running the command crontab -l.

Note: Whenever creates a separate crontab file for your Rails application. So, you can run Cron jobs for your Rails application without affecting other Cron jobs on the system.

By following these steps, you can easily run Cron jobs in your Rails application using whenever.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github