How To Cron

Cron is an exceptionally useful tool in the Linux / BSD world where administrative tasks can easily be rolled up into shell, php, perl, and python scripts among other things.

First it is important for us to setup the environment – There are a few text editors – I personally use NANO / however VI would work just as easy…

Since backups are traditionally something that you would want to automate – lets pretend we are setting up a cron to back things up.

First lets examine the 7 fields in a cron entry.

Field Meaning (input)
1 Minutes (0-59)
2 Hours (2-24)
3 Day of the Month (1-31)
4 Month (1-12) January thru December
5 Day of the week (0-6) Sun thru Sat
6 User to execute the command
7 Command to execute

0 2 * * * root tar czf /var/backup/www.tar.gz /var/www >> /dev/null 2>&1

With the above example and the table of what each field does, you get can put together that at 0200 or 2:00 AM every day root will be running “tar czf /var/backup/www.tar.gz /var/www >>/dev/null 2>&1″ which is telling tar to tar up /var/www into /var/backup/www.tar.gz and /dev/null 2>&1 is a way to have the command put any output into a “trash can” if you will

If needed – you can specify a log file for that output to go with “>> /var/log/cronforcommand.log 2>&1″.  The * in a schedule means to omit that portion of the schedule.

That one was pretty basic however this can get a little more complex.

To make things easier I will skip the user and the command below – and just show a number of examples for scheduling with cron:

EXAMPLES:

Every Minute – * * * * *

Every 5 Minutes – 0,5,10,15,20,25,30,35,40,45,50,66 * * * *

Every 5 Minustes (Simple) – */5 * * * *

Every Hour – * */1 * * *

Every 2 hours – * */2 * * *

Every Day @2:00 AM – 0 2 * * *

Every Day @ 6:00 PM – 0 18 * * *

Every Sunday @ 3:15 AM – 15 3 * * 0

On February 11 @ 10:00 PM – 0 22 11 2 *

Now imagine what you can do and automate with Cron!