Scheduling Commands with Crontab

A common thing to want to do is to schedule a command to run at a specific time. We can do with with cron using the crontab command. By default, all users have permissions to use crontab; however, this can be changed by the existence of one of two files:
  • /etc/cron.allow - Only users listed in this file can use crontab
  • /etc/cron.deny - Users listed in this file cannot user crontab

To see what you have scheduled via crontab, you can run the following command:

$ crontab -l

If you want to see what is scheduled to be run as a different user, you can use the following:

# crontab -u [username] -l

Where you would replace [username] with the appropriate username. Entries in the crontab file have the following syntax:

[m] [h] [dom] [mon] [dow] [command]

Now, I'll explain the above:
  • [m] - Minute to run; represented as a number: 0-59
  • [h] - Hour to run; represented as a number in: 0-23
  • [dom] - Day of Month to run; represented as a number: 1-31
  • [mon] - Month to run; represented as a number: 1-12
  • [dow] - Day of Week to run; represented as a number: 0-6 (Sunday is 0)
  • [command] - Command to run

All of the timing options above can be replaced by an * where necessary to have your command run for all possibilities of that option. For example, in my post on locating files I mentioned scheduling the updatedb command. Let's say we want to schedule this command to run every morning at 6:30 am, then we would put the following into the root user's crontab file:

30 6 * * * updatedb

You can also use a comma separated list for the timing options to have a command run at multiple timings. For example, I have the bad habit of staying on my computer too late at night when I should be going to bed. To try to correct this, in the past, I have scheduled my computer to shutdown at 11:00 pm on Sunday through Thursday nights:

55 22 * * 0,1,2,3,4 shutdown -h +5

Now that we see the necessary syntax for entries in the crontab file, how do we use the crontab command to edit the file to schedule our commands? We can use the following to create or edit a user's crontab file:

$ crontab -e

The above will open your current user's crontab file in the current user's default text editor. Once here, you simply need to put in the entries you would like using the above syntax to schedule them. There are some other options that you can use with the crontab command:
  • -l [username] - Displays [username]'s crontab file
  • -r [username] - Removes [username]'s crontab file
  • -u [username] - Runs the specified contab command on [username]'s crontab file

That pretty much does it for a basic introduction to scheduling commands with crontab.

See you next time

1 comment:

  1. The crontab file looks pretty cool, but I heard a rumor that even though you set your computer to shut of at 11 pm that you keep over riding the shut down, so how do set the command so you can't over ride it easily?