cron and crontab
cron is the classic Unix daemon that runs commands on a schedule. Each user has a crontab, edited with crontab -e, in which every line has five time fields (minute, hour, day of month, month, day of week) followed by the command. System jobs live in /etc/crontab and /etc/cron.d/.
1The time fields
'30 2 * * *' means 02:30 every day; '*/10 * * * *' every ten minutes; '0 9 * * 1' 09:00 every Monday. Day of week 0 and 7 are Sunday.
2System files
Files in /etc/cron.d/ and /etc/crontab have an extra field, the user name, between the time and the command. Directories such as /etc/cron.daily hold scripts run once a day.
3Common pitfalls
cron runs with a minimal environment: use full paths or set PATH in the crontab. Output is mailed to the owner or lost; redirect it to a log file. The % character has a special meaning in crontab lines and must be escaped as \%.
4systemd timers
On systemd distributions, .timer units are an alternative with logging in the journal, randomised delays and catch-up of missed runs (Persistent=true).
How to add a daily job
- Open your crontab:
crontab -e - Add a line, for example: 30 2 * * *
/usr/local/bin/backup.sh>>/var/log/backup.log2>&1 - Save and exit; cron picks up the change automatically.
- List the jobs:
crontab -l
Cautions
crontab -rdeletes the whole crontab without asking.- Test the command by hand with the same user before scheduling it.
Related articles
- systemd units and systemctlWhat a systemd unit is, the common unit types, and how to start, stop, enable and inspect services with systemctl.
- logrotateWhat logrotate does, how its configuration in /etc/logrotate.conf and /etc/logrotate.d works, and how to test a rule safely.
- journalctl and the systemd journalHow to read logs with journalctl, check how much space the journal uses and shrink it safely with --vacuum options.
Sources
- crontab(5) man7.org
- crontab(5) (Debian) manpages.debian.org
- systemd.timer(5) man7.org
Last reviewed: