Course contents · Lesson 18 of 19

Cron Jobs Explained: Schedule Tasks on Linux

Shell Scripting · Lesson 18 of 19 · 11 min Hands-on

Your server should back itself up every weekday at 2:30am, while you sleep. On Linux, the tool for that is cron, and the tasks it runs are called cron jobs. This lesson shows how to write their schedules, install them, avoid the traps that make a job fail silently, and check that it ran.

What cron is

cron is a daemon: a service that runs in the background with no terminal, like those in lesson 12. Its unit is cron.service on Debian and Ubuntu and crond.service on Fedora and Red Hat. Once a minute it wakes up, reads its schedules and starts every command that is due.

The schedules live in a crontab, short for cron table: a text file with one job per line, and each user can have one. A cron job is one of those lines: when, then what to run. cron also looks for changed crontabs every minute, so you never restart it after an edit.

The five time fields

A line starts with five fields separated by spaces: minute, hour, day of month, month and day of week. Everything after them is the command, which cron runs with /bin/sh. The diagram reads a backup line field by field.

The crontab line 30 2 * * 1-5 /home/anita/backup.sh >> /var/log/backup.log 2>&1 split into labelled parts. Five time fields say when: minute 30, allowed 0 to 59; hour 2, which is 2am, allowed 0 to 23; day of month *, any day, allowed 1 to 31; month *, any month, allowed 1 to 12 or jan to dec; day of week 1-5, Monday to Friday, allowed 0 to 7 with Sunday as 0 or 7. The rest is the command, run by /bin/sh: the script by its full path, >> /var/log/backup.log to append its output, and 2>&1 for its errors. A banner says it runs at 02:30, Monday to Friday, in the server's time zone
Five fields say when and the rest says what: this line fires at 02:30 on weekdays only.

The end of the line is redirection from lesson 8, appending output and errors to the log. The job runs as anita, so she must be able to write that file: an admin creates it once with sudo touch and hands it to her with sudo chown anita (lesson 6).

Four special characters build patterns. * means every value. A comma makes a list, a dash a range, and a slash a step, every nth value. In day of week, 0 and 7 both mean Sunday, and names such as mon work too. Examples:

ScheduleWhen it runs
*/5 * * * *every 5 minutes
0,30 9-17 * * *on the hour and half hour, 09:00 to 17:30
0 9 * * 1Mondays at 09:00
@rebootonce, when cron starts at boot

A step counts from the start of the range, not from when you saved the line: */15 in the minute field means minutes 0, 15, 30 and 45. In the timeline, notice where the first run lands.

Timeline of two schedules on the server's clock. Top: */15 * * * * runs every 15 minutes; an hour from 09:00 to 10:00 has runs at 09:00, 09:15, 09:30, 09:45 and 10:00. A marker shows the crontab saved at 09:07, and an arrow shows the first run at 09:15, not 09:22: minutes 0, 15, 30 and 45 of every hour, 96 runs a day. Bottom: 0 9 * * 1 runs on Mondays at 09:00; a week strip from Monday to Sunday has one run, on Monday at 09:00, then the next Monday. A note says day of week 1 is Monday, and 0 or 7 is Sunday
A step follows the clock: saved at 09:07, an every-15-minutes job first runs at 09:15.

Watch one rule: if both day of month and day of week are set, the job runs when either matches. 0 9 1 * 1 runs on the 1st of every month and on every Monday, not only on a Monday the 1st.

Editing crontabs: crontab -e and /etc/cron.d

On Debian and Ubuntu, cron keeps each user's crontab in /var/spool/cron/crontabs, but you never edit those files directly. The crontab command does it for you and checks your lines:

  • crontab -e opens your crontab in the editor named by VISUAL or EDITOR: environment variables, variables (lesson 17) that the shell passes to programs it starts. Without either, it uses the system's default editor; EDITOR=nano crontab -e picks nano for one edit. When you save and leave, it prints crontab: installing new crontab. It refuses a broken line and asks whether to retry the edit.
  • crontab -l lists your crontab, or prints no crontab for anita if you have none.
  • crontab -r deletes your whole crontab, without asking. The r key sits next to e, so type carefully.
  • sudo crontab -u anita -l lists another user's crontab.

Jobs that belong to the system rather than to one person go in /etc/crontab or in a file in /etc/cron.d/. These have one extra field between the schedule and the command: the user to run as. The backup job as a system file looks like this:

# /etc/cron.d/backup: weekday backups, run as anita
30 2 * * 1-5  anita  /home/anita/backup.sh >> /var/log/backup.log 2>&1

On Debian and Ubuntu, files in /etc/cron.d must be owned by root, and their names may contain only letters, digits, hyphens and underscores: backup runs, but backup.cron is ignored. Every line, the last one included, must end with a newline.

The usual traps

cron runs your command in a much smaller world than your terminal, so a job that works when you type it can fail:

  • A minimal PATH. On Debian and Ubuntu, a job's PATH, the folders searched for a command's name (lesson 16), is only /usr/bin:/bin. A program in /usr/local/bin or /usr/sbin is then not found.
  • Relative paths. A job starts in your home folder, not in the script's folder, so a relative path such as data/ points somewhere else. Use absolute paths for every program and file; for programs, a PATH= line at the top of the crontab also works.
  • No terminal. Nobody can answer a question, so a command that asks for a password, such as sudo, fails. Your ~/.bashrc is not read either, so variables you set there are missing.
  • Percent signs. In a crontab line, % ends the command and becomes a newline, so date +%F breaks the line. Write \%, or keep such commands in the script.
  • The time zone. The schedule uses the server's time zone, often UTC on cloud servers, not yours. date or timedatectl shows it.
  • Lost output. cron mails whatever a job prints to its owner. Many servers have no mail system, or MTA (mail transfer agent), so Debian logs No MTA installed, discarding output and the messages are gone. Redirect both streams to a log, as in the backup line.

Did it run? Logs, and systemd timers

Look in two places. cron's own log records every job it starts: on Debian and Ubuntu, read it with journalctl from lesson 13, or in /var/log/syslog if rsyslog is installed; on Red Hat, it is /var/log/cron. Here grep keeps today's lines that mention CMD:

$ sudo journalctl -u cron --since today | grep CMD
Dec 02 02:30:01 web1 CRON[2345]: (anita) CMD (/home/anita/backup.sh >> /var/log/backup.log 2>&1)

The time, host and process ID are illustrative. CMD says that cron started the command as anita, and nothing about whether it worked: for that, read the job's own log, the file the line redirects to. When neither log shows anything, work down the flowchart.

Flowchart for a cron job that did not run. Start: no sign the job ran. Is cron running, checked with pgrep cron? If no, start it with sudo systemctl start cron. If yes, is the line valid, checked with crontab -l? If no, fix it with crontab -e: five fields, then the command. If yes, is the script executable, with a full path, checked with ls -l backup.sh? If no, run chmod +x and use full paths, in the line and in the script. If yes, does a log show an error, checked with journalctl -u cron? If yes, read the error in cron's log, then your own log, and fix that cause. If no, capture the job's output by adding >> log 2>&1 to the line, then wait a minute and look again
Work from the outside in: is cron alive, is the line right, can the script run, what did it say?

Newer systems also have systemd timers: a .timer unit that starts the .service unit of the same name on a schedule such as OnCalendar=Mon..Fri 02:30. The job's output lands in the journal, systemctl list-timers shows the next run, and Persistent=true catches up on a run missed while the machine was off.

Check yourself

You save */10 * * * * at 14:03. When does the job first run?

At 14:10. A step counts from minute 0 of the hour, so the job fires at :00, :10, :20 and so on, whenever you saved it.

A job calls backup-tool, from /usr/local/bin. It works in your terminal, but the job's log says not found. Why?

cron's PATH is only /usr/bin:/bin, so the shell never looks in /usr/local/bin. Write /usr/local/bin/backup-tool in full, or add a PATH= line to the crontab.

journalctl shows a CMD line for your backup every night, but no backup file appears. What does that tell you?

cron and the schedule work, because cron started the command. The command itself failed, so read the job's own log, which 2>&1 fills with its errors.