Cheatsheet - cron
Show or delete current crontab
# Shwo current cron jobs
$ crontab -l
$ crontab -u username -l
# Delete current cron jobs
$ crontab -r
# Delete job for specific user. Must be run as root user ##
$ crontab -r -u username
Edit the crontab
$ crontab -e
cron job format:
1 2 3 4 5 USERNAME /path/to/command arg1 arg2
- - - - -
| | | | |
| | | | ----- Day of week (0 - 7) (Sunday=0 or 7)
| | | ------- Month (1 - 12)
| | --------- Day of month (1 - 31)
| ----------- Hour (0 - 23)
------------- Minute (0 - 59)
Examples:
# run at 3am every day
0 3 * * * /path/to/command
# run at five minutes after midnight, every day
5 0 * * * /path/to/command
# run at 2:15pm on the first of every month
15 14 1 * * /path/to/script.sh
# run at 10 pm on weekdays
0 22 * * 1-5 /path/to/script.sh
# run at 23 minutes after midnight, 2am, 4am …, everyday
23 0-23/2 * * * /path/to/script.sh
# run at 5 after 4 every Sunday
5 4 * * sun /path/to/script.sh
Operators
*: specifies all possible values for a field, e.g. every hour or every month.,: specifies a list of values, e.g.1,5,10,15,20,25.-: specifies a range of values, e.g.5-15/: specifies a step value, e.g.0-23/2or*/2for every two hours.
Special Strings
| Special string | Meaning |
|---|---|
@reboot |
Run once, at startup. |
@yearly |
Run once a year, 0 0 1 1 *. |
@annually |
(same as @yearly) |
@monthly |
Run once a month, 0 0 1 * *. |
@weekly |
Run once a week, 0 0 * * 0. |
@daily |
Run once a day, 0 0 * * *. |
@midnight |
(same as @daily) |
@hourly |
Run once an hour, 0 * * * *. |
e.g.
@hourly /path/to/command
Files
/etc/crontab: system crontabs file. Usually only used by root user or daemons to configure system wide jobs./var/spool/cron/or/var/cron/tabs/: personal user crontab files. It must be backup with users home directory. All individual user must must use crontab command to install and edit their jobs./var/log/cron: logs./var/log/syslog: logsgrep CRON /var/log/syslog.
| Directory | Description |
|---|---|
/etc/cron.d/ |
Put all scripts here and call them from /etc/crontab file. |
/etc/cron.daily/ |
Run all scripts once a day |
/etc/cron.hourly/ |
Run all scripts once an hour |
/etc/cron.monthly/ |
Run all scripts once a month |
/etc/cron.weekly/ |
Run all scripts once a week |
/etc/crontab schedules /etc/cron.hourly, /etc/cron.daily, /etc/cron.weekly, /etc/cron.monthly. Scripts in those folders will be executed.
cron is managed by systemd
# Check status
$ sudo systemctl status cron
# Check logs
$ sudo journalctl -u cron
Email alert
To set the email address, define MAILTO variable:
MAILTO="[email protected]"
@daily /path/to/command
# disable email alert, set MATILTO to ""
MAILTO=""
@daily /path/to/command