How to run Cron jobs in Rails?

Better Stack Team
Updated on May 26, 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:

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, at: '4:30 am' do
  runner 'MyModel.my_task'

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.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →

Reliability is the
ultimate feature

Delightful observability tools that turn your logs & monitoring into a secret weapon for shipping better software faster.

Explore Better Stack