Skip to content

Intermediate · Automation basics: scheduling, archives and shell scripts · topic 34 of 57 · 30 min

Scheduling with cron and crontab

Explanation

cron runs commands on a schedule. Each user has a crontab, edited with crontab -e, where 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/, which have an extra user field.

Why schedule?

Many admin jobs repeat: back up the database every night, delete old temporary files every week, send a disk report every morning. Doing them by hand is boring, and people forget. cron is the classic scheduler: the crond service wakes up every minute, checks all schedules and runs what is due.

The five time fields

output
# ┌───────────── minute (0-59)
# │ ┌─────────── hour (0-23)
# │ │ ┌───────── day of month (1-31)
# │ │ │ ┌─────── month (1-12)
# │ │ │ │ ┌───── day of week (0-7, 0 and 7 = Sunday)
# │ │ │ │ │
  30 2 * * *   /usr/local/bin/backup.sh
Every day at 02:30.
SymbolMeaningExample
*every value* in hour = every hour
,a list1,15 in day of month = 1st and 15th
-a range1-5 in day of week = Monday to Friday
/a step*/10 in minute = every 10 minutes
LineRuns
*/5 * * * *Every 5 minutes
0 9 * * 1-509:00 on weekdays
0 0 1 * *Midnight on the 1st of every month
15 18 * * 018:15 every Sunday
0 */6 * * *At minute 0 every 6 hours (00:00, 06:00, 12:00, 18:00)
Careful: If BOTH day of month and day of week are set (not *), cron runs when EITHER matches. 0 9 13 * 5 runs on every 13th AND on every Friday, not only on Friday the 13th.

Editing your crontab

bash
$ crontab -e                  # opens your crontab in the editor (vi by default)
$ crontab -l                  # list it
30 2 * * * /usr/local/bin/backup.sh >> /var/log/backup.log 2>&1
# crontab -u asha -l          # root: someone else's crontab
# crontab -r                  # remove your WHOLE crontab (careful)
User crontabs are stored in /var/spool/cron/<user>. Do not edit them directly; use crontab -e.

System-wide jobs

/etc/crontab and files in /etc/cron.d/ have the same five fields, then a USER field, then the command. Packages drop files into /etc/cron.d. There are also /etc/cron.hourly, cron.daily, cron.weekly and cron.monthly directories: put an executable script there and it runs at that interval. On RHEL the daily, weekly and monthly ones are run by anacron, which also catches up on jobs missed while the machine was off.

output
# /etc/cron.d/reports
MAILTO=ops@example.com
0 7 * * 1-5  reports  /opt/reports/daily.sh
Field 6 is the user the command runs as.

The cron environment

cron runs your command with a very small environment: a short PATH (often /usr/bin:/bin), no aliases, and your home directory as the working directory. A script that works in your terminal may fail under cron because a command is not found. Use full paths, set PATH at the top of the crontab or script, and always redirect output to a log. Output that is not redirected is mailed to the user, which on most servers means it is lost.

Access control: if /etc/cron.allow exists, only users listed in it may use crontab; otherwise everyone not in /etc/cron.deny may. Job runs are logged in /var/log/cron.

Common mistakes

  • Six time fields in a user crontab, or five in /etc/crontab. User crontabs have no user field; system files do.
  • A % in the command: cron treats % as a newline. Escape it as \%, for example date +\%F.
  • Relying on PATH or relative paths. Use /usr/bin/python3, /opt/app/run.sh.
  • No log redirection, so you never see why the job failed.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Scheduling with cron and crontab · 1/6

crond

cron runs commands on a schedule. crond checks every minute.

Prefer a video by a teacher? Find free videos on “crontab tutorial linux cron syntax examples” on YouTube ↗

In real life: Nightly backups for a Kochi clinic chain

A clinic chain in Kerala keeps patient appointment data on a small RHEL server. The admin schedules a database dump at 01:30 every night and a cleanup of dumps older than 14 days at 02:00 on Sundays. Each job writes to a log, and the team checks /var/log/cron and the log files every Monday.

bash
# crontab -l
30 1 * * *  /usr/local/bin/db-dump.sh >> /var/log/db-dump.log 2>&1
0 2 * * 0   /usr/bin/find /backup -name "*.sql.gz" -mtime +14 -delete
# grep db-dump /var/log/cron | tail -1
Oct 19 01:30:01 clinic01 CROND[50211]: (root) CMD (/usr/local/bin/db-dump.sh >> /var/log/db-dump.log 2>&1)

Practice (0/3 done)

Task 1 · Question

When does "0 22 * * 1-5 /opt/report.sh" run?

Task 2 · Code · Python

Write parse_cron(line) for a USER crontab line. Return a dict with minute, hour, dom, month, dow (strings) and command (the rest of the line, spaces kept). Return None for blank lines, comments (starting with #) and variable lines like "MAILTO=x" (the first word contains "=").

Task 3 · Code · Python

Write matches(field, value) that says whether one cron field matches a number. Support "*", a single number "5", lists "1,15", ranges "1-5", steps "*/10", and lists of these mixed ("1-5,10"). Example: matches("*/15", 30) is True; matches("1-5", 6) is False.

Quick quiz

Question 1

1.Which line runs every 15 minutes?

Question 2

2.What is the extra field in /etc/crontab compared with a user crontab?

Question 3

3.A script works in your terminal but fails from cron with "command not found". Most likely?

Question 4

4.What does crontab -r do?

Question 5

5.Where does RHEL log cron job runs?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

Which line runs every 15 minutes?

Answer: */15 * * * *

*/15 in the minute field.

What is the extra field in /etc/crontab compared with a user crontab?

Answer: The user to run as

System crontabs name the user before the command.

A script works in your terminal but fails from cron with "command not found". Most likely?

Answer: cron uses a minimal PATH; use full paths

Set PATH or use absolute paths.

What does crontab -r do?

Answer: Removes your whole crontab

It deletes the crontab without asking.

Where does RHEL log cron job runs?

Answer: /var/log/cron

Each run is logged in /var/log/cron.

What does the cron line "0 9 * * 1-5 /opt/report.sh" do?Related

Answer: Runs at 09:00 Monday to Friday

Minute 0, hour 9, any day of month, any month, weekdays 1 to 5 (Monday to Friday).

From Bash scripting, text tools and cron

Which service must run for at jobs to execute?Related

Answer: atd

atd runs at jobs.

From One-time jobs with at, and systemd timers

What is the 7th field of an /etc/passwd line?Related

Answer: Login shell

The last field is the login shell.

From Users, groups and the files behind them

Where does RHEL log sudo commands?Related

Answer: /var/log/secure (and the journal)

Authentication and sudo events go to /var/log/secure.

From sudo and the sudoers file

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 4 more topics in “Automation basics: scheduling, archives and shell scripts” before its exam: One-time jobs with at, and systemd timers, Archives and compression: tar, gzip, bzip2 and xz, Bash scripts: variables, quoting, arguments and exit codes, Bash scripts: conditions, loops and safe habits.
  2. Module 7 exam: Automation basics · 14 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Boot, recovery and containers. 57 topics left in the course before the final exam.

← Previous: SSH: keys, ssh-copy-id and hardening sshd