Tech Tip: Schedule tasks with cron

Scheduling application execution is useful in several ways. It allows you to execute a script at certain times of the day, define what day to execute it, run a program to perform a certain task if the conditions are right, and more.

Cron is a program that allows you to accomplish this, but the configuration isn't always intuitive. Cron uses flat text files for configuration as well as to determine what it needs to run and when.

A typical configuration file, called a crontab, may look like the following:

02 4 * * * /scripts/somescript

This tells cron to execute the script /scripts/somescript at 04:02 every day. Here's a breakdown of how the sections of the crontab file determine time:

[minute] [hour] [day of month] [month] [day of week]

If you wanted something to run every hour, you would use the following:

01 * * * * /scripts/hourly

This will run every hour on the first minute (00:01, 01:01, etc.). You can also specify ranges. For example, if you wanted something executed every five minutes on Mondays, you would use this:

*/5 * * * mon /scripts/fiveminutes

This tells cron to step every five minutes on Monday. You could also use it like this:

00,05,10,15,20,25,30,35,40,45,50,55 * * * mon /scripts/fiveminutes

With this method, you could stagger an action at irregular intervals by using something like "10,35,45."

Creating the crontab file is the first step. Telling cron what you want it to do is the second step. To do this, import your crontab file so cron can perform tasks for you by using the crontab program:

$ crontab my-crontab

This tells crontab to import the contents of the my-crontab file. Cron will execute the scripts as the user that imported the file.

Editor's Picks

Free Newsletters, In your Inbox