How to: Use crontab to schedule tasks

If you want to schedule to run a command or script periodically, crontab will be a very useful tool. To add a command or a script to the crontab schedule, the command you need to use is:
 sudo crontab -e  

On my Arch Linux box, the default text editor is "vi" but on Linux Mint, when you run this command the first time, you will be asked to choose a text-editor. And similarly, the crontab file of Arch Linux is pure blank when the one of Linux Mint has many useful comment lines for you to understand how to use crontab. Here is the how the crontab file looks on Linux Mint (the text editor is nano ):

crontab linux

The comment lines in the image above explain quite well about how to use crontab. The format to schedule a task with crontab is:
 * * * * * /any/command/or/script  

As you can see, there are 5 stars ( with a space between 2 stars) and each star represents one part of the date format in the following order:

- minute ( value = 0 -> 59)
- hour ( 0 -> 23)
- day of month ( 1 -> 31)
- month ( 1 -> 12)
- day of week ( 0 -> 6 with 0 = Sunday)

In short, to set a certain period to run a script, you just need to replace each star with a specific value.

Note: If you dont need to set any value for a star, just leave the star in the command. A star means "every" so a command with all 5 stars will mean to run a task every minute until you delete this command from the crontab schedule.

 For example, to run a script at 7:00 AM on every Monday in the first three months of the year, the command will be:
 0 7 * 1-3 1 /path/to/the/script  

As you can see, crontab is quite flexible with it format. You can use 1-5 in the day of week value to schedule a task to be run on work days. Or to run something on Monday, Tuesday and Thursday only, you can use 1,2,4 for the day of week value. For example, to run a script every 20 minutes on Monday, Tuesday and Thursday in January, Feb, May and Oct, the command will be:
 0,20,40 * * 1,2,5,10 1,2,4 /path/to/the/script  

Crontab also has some special  keywords for you to use:
 @reboot  at startup  
 @yearly   once a year    
 @annually  ( == @yearly)  
 @monthly  once a month    
 @weekly   once a week   
 @daily    once a day    
 @midnight  ( == @daily)  
 @hourly   once an hour    

If you use the keywords, you dont need to use the stars. For example, to run a script once everyday, the command will be:
 @daily /path/to/the/script  

And after you insert the right command the crontab file, just save the file and everything is scheduled now. To check the task you have scheduled with crontab, the command to use will be:
 sudo crontab -l  
linux tips and tricks