Skip to content

Run jobs on a schedule: cron and crontab

AdvancedLesson 43 of 669 min

Schedule a nightly backup and a job every five minutes with crontab, read the five time fields, send output to a log and watch the jobs run in your browser.

Backups at 2 in the morning, a report every Monday, a check every five minutes: nobody wants to type those by hand. cron is the program that runs commands on a schedule, and each user's list of jobs is their crontab. The system here is a simulation in your browser: no real accounts, passwords or software are involved. Its clock moves a minute for every command you type, so you can watch jobs run without waiting.

A crontab line

Five time fields, then the command:

30 2 * * * ~/bin/backup.sh
│  │ │ │ │
│  │ │ │ └ day of the week (0 to 7, Sunday is 0 or 7; or mon, tue…)
│  │ │ └── month (1 to 12)
│  │ └──── day of the month (1 to 31)
│  └────── hour (0 to 23)
└───────── minute (0 to 59)

* means every value. So this runs at 02:30, every day.

LineRuns
30 2 * * *every day at 02:30
*/5 * * * *every 5 minutes
0 9 * * 1-5at 09:00, Monday to Friday
0 0 1 * *at midnight on the 1st of every month
@daily, @hourly, @rebootonce a day, once an hour, at every start-up

Installing jobs

crontab -e opens your crontab in an editor (here, the practice Vim): add a line for each job, save and quit with :wq, and cron checks the lines and installs them. crontab -l lists your jobs.

crontab -l

Scripts can't use an editor, so there are two other ways. crontab FILE replaces your whole crontab with the lines in a file, and this adds one line to what's there:

(crontab -l 2>/dev/null; echo "0 9 * * 1 ~/bin/report.sh") | crontab -

crontab -r removes your crontab.

Things that catch people out

  • A job's output is emailed to you unless you send it somewhere: >> ~/heartbeat.log 2>&1 adds it to a log file, errors included.
  • cron runs jobs with very few settings: a short PATH, no aliases, starting in your home folder. Use full paths, like ~/bin/backup.sh.
  • In a crontab, % means a new line, so date +%F must be written date +\%F there, or put in a script instead.
  • grep CRON /var/log/syslog shows each time cron started a job.

Your turn

Schedule two jobs: (1) ~/bin/backup.sh every day at 02:30; (2) ~/bin/heartbeat.sh every 5 minutes, with its output added to ~/heartbeat.log. Then (3) keep working (or sleep 600) until the heartbeat has run at least twice.

Next