# How to run Cron jobs in Rails?

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:

[info]
## 🔭 Want to get alerted when your Cron doesn’t run correctly?
Go to [Better Stack](https://betterstack.com/uptime/) and start monitoring in 5 minutes.
[/info]

## Install `whenever` gem

Add the `whenever` gem to your Gemfile and run `bundle install`:

```ruby
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:

```ruby
bundle exec wheneverize .
```

## Define your Cron jobs

Define your Cron jobs in `config/schedule.rb`:

```ruby
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.

```ruby
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`).

```ruby
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`.

[ad-uptime]