Linux Crontab helps you to run commands, apps or scripts at a custom specific interval. You can schedule the run at the required interval. Crontab runs in background as daemon and check crontab file at /etc/crontab and /etc/cron.*/ directories. These include cron.d/, cron.daily/, cron.hourly/, cron.monthly/, cron.weekly/ directories. In this article, we'll discuss the cron expressions and how to configure your commands to run daily, weekly or every minute as per your requirement through Linux Crontab.
How To Use Crontab?
In Linux, every user has its own cron file which can be edited by using crontab command.
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 -
Open crontab file
NOTE: If you are opening crontab for the first time, it will prompt you to choose the editor before using. Choose editor of your preference.
When opened you will see few commented lines that explain the usage and cron example. One more thing, below is the screenshot of cron file in “Ubuntu”. I have customised my Ubuntu to look like Mac. So don't get confused that I am using Mac.
Linux Crontab Expressions
Let's understand that how we can use cron expressions to configure commands to run at specific time interval. It might look a little difficult but believe me it's easy.
The cron expressions are mainly divided into two parts :
Cron operators add flexibility in defining command timings.
* : Asterisk (*) is for every possible value, for example, * in minute would mean every minute
Example (Run everyday at 5 am)
, : Comma specifies the list of values.
Example (Run everyday at 5 am, 7 am and 10 am)
- : dash specifies range of values.
Example (Run at 5,6,7 am daily)
/ : 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
Example Run every 3 hours
Cron Expressions Usage
Let’s take some more examples to understand the usage of cron expressions.
Run backup script every 5 mins
Run backup script every 5 hours
Run backup script every sunday at midnight
Special Crontab Strings
Besides operators, there are special strings defined by cron that are very easy to use.
Special Crontab strings
Syntax To Use Special Strings
Run the backup script weekly
Run the backup script daily
Viewing Existing Cron Configurations
To list out user's existing cron configurations you can use command -
List existing cron
Generating Linux Crontab Expressions With Tool