Scheduling tasks with Cron

It's often necessary to automatically run a program on a regular basis, often a Rails rake task. The Cron system will do this for you, just tell it what to run and how often.

Adding a Cron task

Login as the rails user and run the following command:

crontab -e

This opens up the Cron configuration file for the current user (in this case, the rails user).

One task is defined per line with each line having five time and date fields and then the command to run.

The time and date fields are:

    field          allowed values
    -----          --------------
    minute         0-59
    hour           0-23
    day of month   1-31
    month          1-12 (or names, see below)
    day of week    0-7 (0 or 7 is Sun, or use names)

A field may be an asterisk, which means all. You can also specify steps after an asterisk, so 'every two hours' becomes */2


For example, the following rake task is configured to run every five minutes:

*/5 * * * * cd /home/rails/myapp/current && RAILS_ENV=production rake batch:process

Or run every day at midnight:

0 0 * * * cd /home/rails/myapp/current && RAILS_ENV=production rake batch:process

Or run once a week on Saturday mornings:

0 9 * * 6 cd /home/rails/myapp/current && RAILS_ENV=production rake batch:process

And you can run tasks at a lower priority using the nice command:

0 0 * * * cd /home/rails/myapp/current && RAILS_ENV=production nice -n 19 rake batch:process

When you're done editing the cron config, just save the file and exit the editor and it automatically takes effect.

docs/cron.txt · Last modified: 2009/05/08 18:04 (external edit)