Sunday, May 13, 2012

Create a cron job in linux

Cron is a system daemon used to execute a specific task at specific time intervals. In linux, there is a simple text file called crontab which contains a list of commands to be run at specific times. In order to add an entry in crontab, first you need to open the crontab file. In order to open the crontab file in edit mode, use the following command

crontab -e

Keep in mind you need to edit crontab file with administrator privileges. So, you might have to use sudo crontab -e.

You can add an entry into the crontab file using the following format:

minute (0-59) hour (0-23, 0 = midnight) day (1-31) month (1-12) weekday (0-6, 0 = Sunday) command 

Notice, there is a space between each section. There are total 5 sections, with each section separated by a space. You can use a * (asterisk) for a section if you want to run the command for every instance of that section. A sample crontab instruction is:

10 08 4 2 1 /somedirectorypath/desiredCommand

The above will execute /somedirectorypath/desiredCommand at 8:10am on February 4th plus every Monday in February. If you want to run a command every 5 minutes, use the following instruction:

*/5 * * * * /somedirectorypath/desiredCommand

The first section i.e. */5 is going to be true for a minute which is divisible by 5. Hence, the command will execute every 5th minute. If you want to run a command every minute, then simply have all sections as *.


There is one limitation to the cron job though, the lowest level of granularity is minute. So, you can't run a command after some specific seconds.

No comments:

Post a Comment