Friday, September 12, 2008

Cron & Crontab

As stated in an earlier post, there are cron folders within /etc appropriately named cron.hourly, cron.daily, and cron.monthly. Stick a script into the appropriate folder, and it will be run accordingly. For example, stick a script into the cron.hourly folder, and it will be run every hour.

The crontab file (/etc/crontab) is a way to have even more control. You can edit this file so that a command is run whenever you want. Open it and you will get a sense of how it works. The first five columns tell it when to run your command. The columns are minute, hour, date of month (dom), month, and day of week (dow). Note Sunday is 0 or 7. By filling these in, you can customise when you want your command to run. Use stars for any blanks. See the sources for better examples. In the next column, specify who the command is to be run as. For example, type root to run it as root. Finally, type in the command. Save the file and then exit.

A good example is to automate updates. If you wanted your system to automatically update everyday at 10:00 a.m., you would add a line to crontab like this:
00 10 * * * root apt-get update && apt-get -y upgrade
Note: the "-y" option with apt-get upgrade means to say yes to any prompts

A couple other notes. First, crontab will let you use steps. For example, if you wanted something to run every 15 minutes (and didn't want to specifically tell crontab to run the command at 15, 30, 45, and 60), you could just specify this with the notation "*/15" instead of "15, 30, 45." Second, crontab always sends output somewhere after it has completed its task. By default, it goes to the users mailbox on the system. To just get rid of this output, add "> /dev/null" to the end of the command line. However, you could specify any output file you like. The ">" means to overwrite the previous file. Alternatively, ">>" means to append the file. So, if we wanted the above example run every 15 minutes and the system to simply get rid of any output, we would add the following to crontab:
*/15 * * * * root apt-get update && apt-get -y upgrade > /dev/null

Personally, I like:
@reboot root apt-get update && apt-get -y upgrade && apt-get clean > /dev/null


Sources:
Schedule tasks on Linux (very good)
Automatically update your Ubuntu system
Newbie: Intro to Cron
Crontab man page

No comments: