← Linux and the Command Line
Lesson 51 of 51 · 5 XP
Cron — running on a schedule
Theory
Machine translation, not yet reviewed by a native speaker.
cron is a service that runs commands on a schedule: backups every night, cleaning up logs, checking a website every 5 minutes.
The schedule is edited with the command:
crontab -e # open your schedule in an editor
crontab -l # show it
Each line is five time fields and a command:
┌───────── minute (0–59)
│ ┌─────── hour (0–23)
│ │ ┌───── day of the month (1–31)
│ │ │ ┌─── month (1–12)
│ │ │ │ ┌─ day of the week (0–7, 0 and 7 are Sunday)
│ │ │ │ │
* * * * * command
| entry | when |
|---|---|
*/5 * * * * |
every 5 minutes |
0 3 * * * |
every day at 03:00 |
30 8 * * 1-5 |
on weekdays at 08:30 |
0 0 1 * * |
on the first day of every month |
@reboot |
when the system boots |
An example — a nightly backup of a website:
0 3 * * * tar czf /backup/site_$(date +\%F).tar.gz /var/www/site >> /var/log/backup.log 2>&1
Cron's traps:
- a different environment: the
PATHin cron is short, so write full paths to programs and scripts (/usr/bin/python3,/home/kai/backup.sh); %must be escaped as\%: for cron it's a special character;- nobody sees the output: redirect it to a log (
>> file 2>&1), otherwise errors get lost; - the site crontab.guru is handy for checking an expression.
The modern alternative on systems with systemd is systemd timers (systemctl list-timers).
Our mini Linux has crontab and crond too, but when the page reloads, the schedule disappears. Practise on your own VPS.