How to Use Unix Cron to Schedule Your Jobs
Have you ever had the need to run a particular program in certain periods of time but you just couldn’t do it manually ? Unix and Linux users will certainly face this even once in their systems administration life and it really pays to know of the little but incredible cron tool that you can use in order to automate certain jobs.
Cron is a utility that is used in order to make your own scheduler very easily. The configuration file that is responsible for scheduling these jobs is placed under /etc/crontab. You can easily edit that file using a simple editor like vim or just specifying the command :
The good thing about cron is that the regular user does not need to have root privileges in order to use it. Therefore, everybody can configure their own cronjobs that will run regularly when they want it. The cron syntax is actually rarely remembered by most people, though in fact it is quite easy to do so. Each line represents a different cron job. The first 5 tokens represent the actual time that a job will be executed at and the last one represents the actual command to be executed. This is what the 5 first tokens represent :
minute ( 0-59 ) represents the minute that the command executes hour ( 0-23 ) represents the hour that the command executes day ( 1-31 ) represents the day of the month that the command executes month ( 1-12 ) represents the month that the command executes week day ( 0-6 ) represents the day that the command executes ( Sunday = 0, Monday = 1 .. )
While this syntax seems pretty easy, people have sometimes trouble to specify intervals of 15 minutes or such. I will try to show you how to do that and how easy it is to actually make out the correct cron command token sequence.
In order to simplify the examples, i will have my cron samples run a simple wget command like:
wget -0 - -q http://codercaste.com
This simple command is getting the index page of codercaste.com without producing any output. Of course this could be just any command that you would like to use, but for the sake of simplicity i will just use this one. Let’s now see some different test cases where cron could be useful :
( Every Sunday and Tuesday at 3.50 o’clock )
50 3 * * 0,2 wget -0 - -q http://codercaste.com
( Every Past 15 minutes of Every Hour of Every Day )
15 * * * * wget -0 - -q http://codercaste.com
( Every 3rd Day of a Month, at 3 o clock, in Days Monday to Wednesday )
* 3 3 * 1-3 wget -0 - -q http://codercaste.com
The last one is a bit more difficult, it used the / division operator. Therefore something like */15 for hours, means every 15 minutes of that hour and so :
( Every 15 Minutes between the hours 8am to 1pm )
*/15 8-13 * * * wget -0 - -q http://codercaste.com
Hope this provides you with the examples you need for cron. If you have any question about it, please leave a comment below and i will try to help.