Sub topic 2
Scheduling with cron: syntax and crontab files
This chapter assumes you can edit files on the command line, write a basic shell script, and read logs. It covers how cron decides when to run a job and where you put the schedule. The next chapter covers the environment cron gives your job.
How cron works
cron is a daemon that wakes up every minute. It reads its schedule files, compares the current time to each entry, and starts a command for every entry that matches. It keeps no record of past runs. If the machine is off at the scheduled minute, the run is skipped. Missed runs are covered in a later chapter.
Cron does not check whether the command works. It starts the command, and any error afterwards is yours to find. This is one reason scheduled jobs fail quietly.
The five-field schedule
Each entry has five time fields followed by the command.
# ┌───────── minute (0-59)
# │ ┌─────── hour (0-23)
# │ │ ┌───── day of month (1-31)
# │ │ │ ┌─── month (1-12)
# │ │ │ │ ┌─ day of week (0-7, 0 and 7 are Sunday)
# │ │ │ │ │
# * * * * * command to run| Field | Allowed values | Notes |
|---|---|---|
| Minute | 0-59 | There is no seconds field. One minute is the finest resolution. |
| Hour | 0-23 | 24-hour clock, in the server's time zone. |
| Day of month | 1-31 | A job set for day 31 does not run in months with 30 days. |
| Month | 1-12 or `jan`-`dec` | Names are case-insensitive. |
| Day of week | 0-7 or `sun`-`sat` | Both 0 and 7 mean Sunday. |
Operators
Four operators work in every field.
*matches every value in the field.,makes a list:0,30means minutes 0 and 30.-makes an inclusive range:1-5in the day-of-week field means Monday to Friday./makes a step:*/15means every 15th value, and10-50/10means 10, 20, 30, 40, 50.
Some examples:
0 * * * * /usr/local/bin/hourly.sh # at minute 0 of every hour
*/15 * * * * /usr/local/bin/poll.sh # at :00, :15, :30, :45
30 2 * * * /usr/local/bin/backup.sh # every day at 02:30
0 9-17 * * mon-fri /usr/local/bin/report.sh # on the hour, 09:00 to 17:00, weekdays
0 0 1 * * /usr/local/bin/monthly.sh # midnight on the 1st of each monthSteps restart each cycle
A step counts from the start of its field, not from the last run. */45 in the minute field runs at minute 0 and minute 45 of every hour. The gap between 45 and the next hour's 0 is only 15 minutes. If you need a true interval that does not divide evenly into the field, cron is the wrong tool. Use a systemd timer with OnUnitActiveSec, covered later.
The day-of-month and day-of-week trap
When both the day-of-month and day-of-week fields are restricted (neither is *), standard cron runs the job when either matches. It does not require both.
# Runs on the 13th of every month AND on every Friday, not only Friday the 13th
0 12 13 * 5 /usr/local/bin/unlucky.shTo run only on a particular weekday within a date range, schedule the job on every matching day and test inside the script. This example runs on the first Monday of the month:
0 6 * * mon [ "$(date +\%d)" -le 7 ] && /usr/local/bin/first-monday.shNote the \%. The next section explains why.
Shortcut strings
Most cron implementations accept a few readable replacements for the five fields.
| String | Equivalent | Meaning |
|---|---|---|
| `@hourly` | `0 * * * *` | Start of every hour |
| `@daily` | `0 0 * * *` | Midnight every day |
| `@weekly` | `0 0 * * 0` | Midnight on Sunday |
| `@monthly` | `0 0 1 * *` | Midnight on the 1st |
| `@reboot` | none | Once, when the cron daemon starts |
@reboot runs when cron starts, which is usually at boot. It can also run again if you restart the cron service.
Where schedules live
Cron reads schedules from several places. They differ in who owns the job and whether the line has a user column.
User crontabs
Each user can have a personal crontab. You never edit the underlying file directly (it lives under /var/spool/cron/). Use the crontab command:
crontab -e # edit your crontab in $EDITOR
crontab -l # list it
sudo crontab -u backup -l # list another user's crontab
crontab -r # remove it entirely, with no confirmationLines in a user crontab have the five time fields and then the command. The job runs as that user.
crontab -r sits next to -e on the keyboard and deletes everything without asking. Run crontab -l > crontab.bak before you edit, or use crontab -ri if your version supports the confirmation flag. Keep the real schedule in version control.
System crontabs
The system-wide files take an extra sixth column, the user to run as:
/etc/crontabis the main system file./etc/cron.d/holds one file per application or service. This is the best place for jobs installed by a package or a configuration management tool./etc/cron.hourly,cron.daily,cron.weeklyandcron.monthlyhold plain executable scripts, not crontab lines. They run at times set elsewhere, and the exact time depends on your distribution.
# /etc/cron.d/sync
[email protected]
PATH=/usr/local/bin:/usr/bin:/bin
# minute hour dom month dow user command
*/15 * * * * root /usr/bin/flock -n /run/lock/sync.lock /usr/local/bin/sync.sh >> /var/log/sync.log 2>&1This is the schedule from the chapter plan, adapted for /etc/cron.d with the root user column added. The flock wrapper is explained in a later chapter. Here it only shows what a complete line looks like.
Files in /etc/cron.d are picked up silently or ignored silently, depending on a few rules. On Debian and Ubuntu:
- The filename may contain only letters, digits, underscores and hyphens. A file named
sync.cronis ignored because of the dot. - The file must be owned by root and must not be writable by group or others.
- The file must end with a newline.
If a job in /etc/cron.d never runs, check these three things first.
Variables and the percent sign
A crontab can set variables on their own lines, above the jobs. Two are read by cron itself:
MAILTOis where cron sends any output the job prints. An emptyMAILTO=""turns mail off.SHELLselects the shell. The default is/bin/sh, not bash, so bash-only syntax in a crontab line may fail.
Variable lines do not expand other variables, and you cannot write PATH=$PATH:/opt/bin. Write out the whole value.
The % character has a special meaning in a crontab command. An unescaped % is turned into a newline, and everything after the first one is passed to the command as standard input. This breaks a very common line:
# Wrong: cron cuts the line at the first %
0 1 * * * tar czf /backup/site-$(date +%F).tgz /var/www
# Right: escape each % with a backslash
0 1 * * * tar czf /backup/site-$(date +\%F).tgz /var/wwwA better habit is to put anything beyond a single simple command into a script and call the script from the crontab. The script then has no % problem and can be run by hand for testing.
How cron picks the jobs to run
The matching rule has one special case, which the diagram shows.
When a field is *, it always matches, so the "both" rule in the unrestricted branch behaves as you expect.
Common mistakes
- Using the wrong user. A job in your crontab runs as you. A job that needs to write to
/var/logor read a protected file may need to run as root or a dedicated user. Least privilege is covered in a later chapter. - Relative paths. Cron starts the job in the user's home directory. Write full paths for commands and files.
- Forgetting that times are local. The schedule uses the server's time zone, which causes surprises when the clock changes.
- Testing only by waiting. Run the command by hand first, then temporarily schedule it for the next minute, and only then set the real schedule.
- No log of runs. Cron records that it started a job in the system log, not whether the job succeeded. You can confirm a start with
grep CRON /var/log/syslogon Debian-based systems orjournalctl -u cron(the unit iscrondon Red Hat-based systems).
Exercise
A line in root's crontab reads 0 3 15 * 1 /usr/local/bin/clean.sh. On which days does it run, and what would you change to run it only on Mondays?
Show answer
It runs at 03:00 on the 15th of every month and also on every Monday, because both day fields are restricted and standard cron runs the job when either matches. To run only on Mondays, change the day-of-month field to *: 0 3 * * 1 /usr/local/bin/clean.sh.
Exercise
This line is in /etc/cron.d/dbdump and the job never runs: 0 1 * * * pg_dump mydb > /backup/db-$(date +%F).sql. Name two problems with it.
Show answer
There is no user column between the time fields and the command, so cron treats pg_dump as the user name. The % in +%F is also unescaped, so cron turns it into a newline and cuts the command short. The fix is 0 1 * * * postgres pg_dump mydb > /backup/db-$(date +\%F).sql, or better, move the command into a script.