How to setup cron jobs to automate regular tasks on Linux
Cron is a time-based job that runs in the background at specific intervals or designated times. It allows you to run tasks and scripts automatically, making cron useful for automating maintenance-related tasks. Therefore, it is a very popular server administration tool.
Cron is present in all Linux distributions. However, if it is not installed, you can install it using apt:
sudo apt-get update && sudo apt-get install cron
Add it to autostart and run:
sudo systemctl enable cron
Setting up cron
In order to see all configured cron jobs, run the command:
If you want to set up cron jobs, use the following command:
Note: if this is the first time you’re running the crontab command it will prompt you to select a default text editor to use when editing your crontab.
In every line you can define one command to run (with optional args) and its schedule. The structure is:
minute hour day-of-month month day-of-week command [args]
month: 1-12 or jan-dec
day-of-week: 0-6 where 0 is Sunday
There are special characters you can include in each of the schedule components:
*: an asterisk is a wildcard variable that represents all/any. A task scheduled with * * * * * will run every minute of every hour of every day of every month.
,: commas break up scheduling values to a specific values list. To have a task running every hour and every 15 minutes you can define the following structure 0,15,30,45 * * * *.
-: hyphen represents a range of values. Instead of defining different tasks for a command you want to run for the first 10 minutes of every hour you could just schedule it as 0-9 * * * *.
/: use a forward slash to express a step value. Instead of using separate cron tasks to run a command every three hours you could schedule it to run like this 0 */3 * * *.
Some shortcuts can be defined in your crontab file equivalent to numeric schedule specified below:
@reboot: once, at startup
@hourly: 0 * * * *
@daily or @midnight: 0 0 * * *
@weekly: 0 0 * * 0
@monthly: 0 0 1 * *
@yearly or @annually: 0 0 1 1 *