cron is a background service that runs commands on a schedule: nightly backups, weekly clean-ups and similar work. The package is usually cron on Debian-based systems and cronie on Red Hat based ones, and it may need installing or enabling.
Your crontab
Each user has a table of jobs called a crontab.
crontab -e # edit
crontab -l # list
crontab -r # remove the whole tableBe careful with -r: it is next to e on a QWERTY keyboard and deletes every entry.
The five time fields
minute hour day-of-month month day-of-week command
30 2 * * * /home/maria/backup.shThis runs every day at 02:30. Minutes are 0 to 59, hours 0 to 23, and in day-of-week both 0 and 7 usually mean Sunday.
* means every value. You can also use:
- a list:
1,15 - a range:
1-5 - a step:
*/10
*/10 * * * * /usr/local/bin/check.sh
0 9 * * 1-5 /home/maria/report.shThe first runs every 10 minutes. The second runs at 09:00, Monday to Friday.
One surprise: if you restrict both day-of-month and day-of-week, the job runs when either matches.
Many implementations also accept shortcuts such as @daily and @reboot.
Environment and output
cron does not load your interactive shell setup. It provides only a small environment, so PATH can differ from your terminal's, and it runs commands with sh by default. Use full paths, and capture output:
0 3 * * * /home/maria/backup.sh >> /home/maria/backup.log 2>&1Without redirection, output is mailed to the user if mail is set up, and otherwise may be lost or only logged. A % in the command has a special meaning, so write \%, for example in date +\%F.
System-wide jobs
/etc/crontab and files in /etc/cron.d/ have an extra field, the user to run as:
0 4 * * * root /usr/local/sbin/cleanup.shMany systems also run scripts placed in /etc/cron.daily/, /etc/cron.weekly/ and similar directories. Systemd timers are another scheduling option you may meet.
Try it
Add * * * * * date >> /tmp/cron-test.log with crontab -e. Wait two minutes, read the file, then delete that line. Do the same safely in the processes and cron lab. The crontab manual page describes the format.
Check your understanding
Scheduling with cron
All 5 sections ยท no timer
Unlimited retries
Questions from every section are combined into one assessment. Answer them all correctly to complete the article.
Your completion saves in this browser. Sign in to sync it to your account.