Linux Utility – Understand Linux Crontab Or Cron Expressions To Run Command At Specific Interval
How To Use Crontab?
The section following this explains various fields for cron expression. Cron is pre-bundled in Linux and no need to separately install it. To open crontab file use command –
NOTE: If you are opening crontab for the first time, it will prompt you to choose the editor before using. Choose the editor of your preference.
Linux Crontab Expressions
The cron expressions are mainly divided into two parts :
- Date part: that defines at what interval or time the command has to be executed.
- Command: command to execute.
The expression takes the form –
min hour day month dayOfWeek Command min : Minute (0-59) hour : Hour (0-23) day : Day of month (1-31) month : Month (1-12) dayOfWeek : Day of week (0 - 7) [Sunday = 0 or 7] Command: command to run as cron job.
* : Asterisk (*) is for every possible value, for example, * in minute would mean every minute
0 5 * * 1 sh /home/savan.patel/backup.sh
, : Comma specifies the list of values.
0 5,7,10 * * * sh /home/savan.patel/backup.sh
– : dash specifies range of values.
0 5-7 * * 1 sh /home/savan.patel/backup.sh
/ : Seperater
This is step operator use to specify for terms like every hour. For example to run command at every 3 hours you would use */3 in your expression
* */3 * * * sh /home/savan.patel/backup.sh
Cron Expressions Usage
*/5 * * * * sh /home/savan.patel/backup.sh
Run backup script every 5 hours
* */5 * * * sh /home/savan.patel/backup.sh
Run backup script every sunday at midnight
0 0 * * 7 sh /home/savan.patel/backup.sh
Special Crontab Strings
@reboot : run once at startup @yearly : run yearly on 1st Jan midnight @annually : same as yearly @monthly : run on 1st of month every month midnight @weekly : run once a week @daily : run daily at midnight @midnight : same as @daily
Syntax To Use Special Strings
@weekly sh /home/savan.patel/backup.sh
Run the backup script daily
@daily sh /home/savan.patel/backup.sh
Viewing Existing Cron Configurations