Friday, October 17, 2008

Automating Linux processes with 'cron'

If you have been looking to schedule some type of task on your Linux machine, but aren't sure how to do it, there's cron. cron is the Linux task scheduler, and is a very useful tool. My use has been limited to Red Hat, so I can't vouch for the validity of this for other flavors of Linux. If you try it with another version and run into problems, consult the system documentation for cron's usage. In Red Hat, the system cron tasks are found at /etc/crontab. Any user-defined cron tasks are to be placed at /var/spool/cron. There are also more tasks found at /etc/cron.d. Using your favorite text editor, you can create or modify the cron files to include whatever command(s) you want to execute on a schedule. The syntax for a command within a cron file is as follows:

minute hour day month dayofweek command

Where the values correspond to:

minute: any integer from 0 to 59
hour: any integer from 0 to 23
day: any integer from 1 to 31, depending on the month you choose
month: any integer from 1 to 12 (or the short name of the month)
dayofweek: any integer from 0 to 7 where 0 or 7 represents Sunday (or the short name of the week such as sun, mon, and so on)
command: the command to execute

You can also use * as the wildcard to represent all possible combinations. Some examples:

Reboot the machine at 5am on February 7th
0 5 7 2 * /sbin/init 6

Reboot on Mondays at 7:30pm
30 19 * * 1 /sbin/init 6
OR
30 19 * * mon /sbin/init 6

Reboot every hour on the hour
0 * * * * /sbin/init 6

For more information and a more detailed explanation, check out this page.

No comments: