Cron is an exceptionally useful tool in the Linux world where administrative tasks can easily be rolled up into shell, php, perl, and python scripts among other things. Per a website that I just came across, the word cron comes from the Greek word chronos which means time.
First, lets setup the environment. I use VI as my text editor on Linux and you can view my “60 second VI tutorial” on here as well. To ensure that VI will be our crontab (cron table) editor we will need to edit your “.profile” file for whatever user you are going to be logged in with (typically root).
vi /root/.profile
Add one of thefollowing lines above the second fi to match your preference.
export EDITOR=/usr/bin/vi #if you have just VI installed
export EDITOR=/usr/bin/vim.basic #if you have VIM installed
Ensure that you save it with :wq.
Now that we have that out of the way, lets start scheduling tasks.
Since backups are traditionally something that you would want to automate or schedule, I’ll use it as my main example but first I’ll break down the cron scheduling syntax.
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 Alternately 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 so I’ll get a little more complicated now. Matter of fact, I’ll just skip the user and command to execute from now on and focus on the command structure 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 Feburary 11 @ 10:00 PM – 0 22 11 2 *
That pretty much covers the majority of typical uses for cron. Obviously this is a very powerful tool and can do so much more but for this post, I think it’ll do. If I messed anything up , please let me know. 🙂 Enjoy.