Scheduling a Process with Cron and Crontab

By    | April 2, 2008 | Code Snippets

Cron is a time-based scheduling service in Unix and Unix-like operating systems (including Linux, FreeBSD and Mac OS X). It makes use of a configuration table called crontab that gives details of the commands to run and the schedule to execute them. This guide covers the basics of using cron to setup cronjobs with crontab.

You can read the manual pages for cron or type ‘man crontab’ at the command line for more information.

Using crontab

To view the current state of a crontab you need to specify the -l option. You can view another users crontab by specifying -u username (you’ll need to be root to do this):

user$ crontab -l [-u username]

To edit the state of a crontab you need to use the -e flag:

user$ crontab -e [-u username]

The Format of Crontab

When you edit a user’s crontab for the first time you will presented with an empty file – this is a daunting prospect for the cron newbie! Here’s a minimal example crontab to get you started:

MAILTO=adam@example.com
#minute hour monthday month weekday command
30 12 * * * echo "hello world!"

The first line sets the MAILTO environment variable. Any output that would normally have been printed to STDOUT by the processes will be emailed to this address. We then have a comment so we can remember the order of the variables. Finally, the 3rd line defines what to run and when. In this case, at 12:30 every day of every month we will echo “Hello World!”.

Scheduling a Task

Crontab gives us a very flexible syntax for defining when our commands will run. For each of the 5 periods we can use any of the following notations:

  • * – every value
  • # – one given value e.g. 5
  • */# – every value that divides by the number e.g. */5 will run at 5,10,15,20…
  • #,#,# – we can specify a comma separated list of values e.g. 5,20,24
  • #-# – we can also use ranges of values e.g. 2-5

For each field the following values are valid:

  • minute = 0-59
  • hour = 0-23
  • monthday = 1-31
  • month = 1-12
  • weekday = 0-7 (0 or 7 is Sun)

Installing a Crontab

When you save and exit from editing the crontab the system will parse the contents and schedule the tasks to run.

Further Options

As well as setting the MAILTO flag, you can set any environment variables you need within the crontab file. For example, if you need to add to the path:

PATH=$PATH:/my/new/dir

These declarations are read in order and can be redefined to create sections within the crontab. For example, if you have 1 job that needs to email sales@example.com and another that needs to email sysadmin@example.com, then you can use the following file structure:

MAILTO=sales@example.com
#minute hour monthday month weekday command
30 12 * * * /path/to/my/command
MAILTO=sales@example.com
1 * 1 * * /path/to/my/othercommand


More like this