Run a program or script every 5 or X minutes or hours

Written by
Date: 2012-04-07 09:33:00 00:00


One of the best things computers do, is to execute repetitive jobs, and with *nix systems that is done using cronjob.

I usually want my jobs to run every X amount of time, let's say every 5 minutes, or every 12 hours.

Here is how:

  • Edit your cronjob file by running crontab -e command
  • Add the following line for an every-5-minutes interval.

    */5 * * * * /path/to/script-or-program

  • Save the file, and that is it.

If you want to do it every 12 hours, add this line when editing crontab file.

0 */12 * * * /path/to/script-or-program

That will run on 12 and 0 hours, at 0 seconds.

Of course you can combine.

*/5 */3 * * * /path/to/script-or-program

This will execute every five minutes, only on hours 3, 6, 9, 12 and so on.

If you use that in day of month field, you can end up running your script every X days in a month, but then X-1 or X+1 when changing months, from even to odd days months.

So:

0 0 */2 * * * /path/to/script-or-command

Would result in every two days until the end of the month and then a three day interval when the next month is starting.

Using the method with months of year, can also lead to similar problems.

0 10 01 */3 * /path/to/script-or-program

Will run the command every three months on the first day at 10:00, so, 10:00 first of Jan, Apr, Jul, Oct.

But if you use an interval that does not divid the year in equal parts, like 5.

0 10 01 */5 * /path/to/script

The script will run at 10:00 first day of Jan, Jun, Dec and then Jan again, only one month after the last time.