Know linux’s cron in 10 minutes

Any linux sysadmin will tell you: cron is a must-know, a very powerful tool among the most powerful. In this article I’ll explain you how it works in 10 minutes, tops.

For those of you that doesn’t not know about cron, it’s ascheduling tool. You can use to plan a task every day, every week, every minute and so on.

Crontab conf file format.

To view cron configuration file, type in a terminal:

Here, any new line that not commented out (ie: not beginning with a “#”) is a input command for cron. The basic syntax is the following:

“m” stands for “minute”, “h” for “hour”, “dom” for “day of month”, “dow” for “day of week” and “command” is the command you wish to execute.

Here’s a quick cheat sheet:

# * * * * * command to execute
# ┬ ┬ ┬ ┬ ┬
# │ │ │ │ │
# │ │ │ │ │
# │ │ │ │ └───── day of week (0 - 6) (0 to 6 are Sunday to Saturday)
# │ │ │ └────────── month (1 - 12)
# │ │ └─────────────── day of month (1 - 31)
# │ └──────────────────── hour (0 - 23)
# └───────────────────────── min (0 - 59)

Warning:

  • cron uses the minut as the minimal time unit, meaning you cannot define a job to be executed every second.

  • cron uses 24hour format!

Basic scheduling

Let’s say you want your system to wish you a happy birthday, every year at the same date at 8AM. Let’s say you are born the same day as me, on the 16th of september. Then the command would be:

To decompose this command, we tell cron to execute “/home/wishmehappybirthday.sh” at 8AM (00 minute, 08th hour), every 16th day of the 9th month.

 

“more than once” scheduling

For example, if you want to execute a command twice a day at 8AM and 4PM, every day:

You got it: commas (“,”) are used to specify more than one value in a field.

You can also  execute a command in a range of values using hyphens (“-“). For example, to execute something only between the 5 and the 15 of september, every day at 8AM, every year:

A tricky one: what if I want to execute something every five minutes, all the time? This command will do the job:

but there is a particular syntax for this kind of repetitive job:

This on will do the very same.

One more thing: you can combine ranges with frequencies. For example:

will execute a command every 5 minutes, every first half hour.

 

Special keywords

Cron defines, on some systems, some very useful keywords. Here they are with their equivalent:

  • @yearly -> 0 0 1 1 *

  • @daily -> 0 0 * * *

  • @hourly -> 0 * * * *

  • @reboot -> run on boot.

For example, to send me a notification everytime the computer reboots: