Chapter 1 · Lesson 17 of 19
Server basics

Schedule tasks with cron on Linux

cron is a Linux scheduler that runs commands at set times, configured per user in a file called a crontab.

By the end you will

Schedule a script with crontab, log its output and confirm it ran.

Time
16 min
Level
Beginner
Check
4 questions
You need
  • A Linux server and a script to run

To schedule a task on Linux, run crontab -e and add a line with five time fields followed by the command. A nightly backup, a certificate renewal check and a log cleanup all have one thing in common: nobody should have to remember to run them. cron runs commands at the times you specify. The catch is that cron runs your command in a much barer environment than your terminal, which is why most “it works by hand but not in cron” problems are about paths and output.

How it works#

The cron service (a background daemon, named cron on Ubuntu) wakes up every minute and reads the crontab files. For each line whose time fields match the current minute, it starts the command.

Every user can have a crontab, edited with crontab -e and stored by the system. The system also reads /etc/crontab and the files in /etc/cron.d/, which have an extra column naming the user. In this lesson you use your own user’s crontab.

Cron does not start your shell profile and has none of your environment variables. The command runs under /bin/sh with a small default environment, so PATH is short (typically just /usr/bin:/bin), and variables from your .bashrc are not set. The working directory is your home directory. Anything the command prints is mailed to the user if a mail system exists, and otherwise discarded, so you must send output to a file yourself.

Two details catch people. When both day-of-month and day-of-week are set (not *), a job runs when either one matches. And cron has no memory: if the server was off at the scheduled minute, the job did not run.

Step 1: Open your crontab#

bash
crontab -e

Pick an editor if asked. This edits the crontab for your user only. What you should see: an editor with comment lines at the top (or an empty file). List it later with crontab -l.

Step 2: Learn the five fields#

output
* * * * * command
| | | | |
| | | | +-- day of week (0-7, Sunday is 0 or 7)
| | | +---- month (1-12)
| | +------ day of month (1-31)
| +-------- hour (0-23)
+---------- minute (0-59)

Examples:

output
*/5 * * * *   every 5 minutes
0 3 * * *     every day at 03:00
30 2 * * 1    Mondays at 02:30
@reboot       once at boot (replaces the five fields)

* means every value, */5 means every fifth, 1,15 lists values, and 1-5 is a range.

Step 3: Add a job with absolute paths and logging#

output
0 3 * * * /home/deploy/backup.sh >> /home/deploy/backup.log 2>&1

Use full paths for the script and the log. >> file 2>&1 appends both normal output and errors, so failures are not lost. Make sure the script is executable (see file permissions):

bash
chmod +x /home/deploy/backup.sh

Start the script with a shebang line such as #!/bin/bash, and set PATH yourself near the top of the crontab if needed:

output
PATH=/usr/local/bin:/usr/bin:/bin

Cron uses the server’s timezone, which is often UTC. Check it with timedatectl.

Step 4: Stop overlapping runs (optional)#

If a job can run longer than its interval, wrap it in flock so a second copy does not start:

output
*/5 * * * * /usr/bin/flock -n /tmp/sync.lock /home/deploy/sync.sh >> /home/deploy/sync.log 2>&1

-n makes flock give up at once if the lock is held, so the new run exits quietly.

Check it worked#

For a quick test, temporarily set the job to run every minute (* * * * *), wait, then look at your log file. To see whether cron started the job:

bash
sudo grep CRON /var/log/syslog

On systems without that file, use:

bash
sudo journalctl -u cron --since "10 minutes ago"

You should see lines like CMD (/home/deploy/backup.sh ...) at the expected times, with your user name beside them. Then read your log file; it should hold the script’s own output. Set the schedule back afterwards.

Edge cases and gotchas#

  • The PATH is short. A command found by which docker in your shell may not be found by cron. Use the full path or set PATH at the top of the crontab.
  • A % is a newline to cron. In a crontab line, an unescaped % ends the command and the rest becomes input. This breaks date +%F. Write \% or move the command into a script.
  • Timezone and daylight saving. Jobs follow the server clock. If it is set to a local zone with daylight saving, a job at 02:30 may be skipped or run twice on the change day. Using UTC on servers avoids this.
  • Missed runs are not made up. If the server was off or rebooting at the scheduled minute, the run is lost.
  • Overlapping runs can corrupt data. A slow job plus a short interval can start two copies at once. Use flock as shown above.
  • A new line is needed at the end. Make sure the last line of a hand-edited crontab ends with a newline. Using crontab -e handles this for you.
  • Environment secrets. Do not put passwords on the crontab line. Anyone who can read ps output may see arguments, and the file may be backed up. Read secrets from a protected file in the script.

Troubleshooting#

SymptomLikely causeFix
Log shows command not foundShort PATH in cronUse absolute paths, find them with which <cmd>
Job never appears in the cron logSyntax error in the five fields, or cron is not runningRe-read the fields, then systemctl status cron
Permission denied in the logScript not executable, or log path not writablechmod +x the script and check the log directory
Job runs at the wrong hourServer timezone is not what you expectRun timedatectl and adjust the hour, or set the timezone
Works by hand, fails from cronYour shell has variables and a PATH that cron lacksRun it with env -i /bin/sh -c '<command>' to reproduce the bare environment
Date command output is cut offAn unescaped %Escape as \% or use a script
no crontab for deployThe user has no crontab yetNot an error; create one with crontab -e
Job runs twice or at odd timesTwo crontabs (user and system) hold the same jobCheck crontab -l, sudo crontab -l and /etc/cron.d/
Job output shows nothingOutput went to mail and was discardedRedirect with >> file 2>&1

Real-world scenario#

You write /home/deploy/backup.sh to dump a database and copy it elsewhere. By hand it works. You add 0 3 * * * /home/deploy/backup.sh >> /home/deploy/backup.log 2>&1 and go to bed.

In the morning the log says pg_dump: command not found. Cron’s PATH did not include the directory that holds it. You run which pg_dump, put the full path in the script, and set PATH=/usr/local/bin:/usr/bin:/bin at the top of the crontab.

To avoid waiting a day, you set the schedule to * * * * *, watch the log fill, then set it back to 03:00. The next morning the log has one clean entry.

Quick reference#

ScheduleMeaning
*/5 * * * *Every 5 minutes
0 * * * *Top of every hour
0 3 * * *Daily at 03:00
30 2 * * 1Mondays at 02:30
@rebootOnce at boot
CommandUse
crontab -eEdit
crontab -lList
journalctl -u cronSee runs

Security and safety notes#

  • crontab -r deletes your whole crontab with no confirmation. It sits next to -e on the keyboard, so list and back up with crontab -l > crontab.bak first.
  • Test any job that deletes or overwrites data with a harmless command first.

Next#

When a job or service fails because a port is taken, use Find what is using a port.

Check what you learned4 questions
1What does 30 2 * * 1 mean?
2Why does a script work in the terminal but fail in cron?
3What does >> backup.log 2>&1 do?
4A backup job takes longer than its 5 minute schedule. How can you stop runs from piling up?

Frequently asked questions

Why does my script work in the terminal but not in cron?

Cron runs with a minimal environment and a short PATH. Use absolute paths for the script and any programs it calls, and set variables inside the script.

Where does cron send errors?

By default it tries to mail the user, which usually goes nowhere. Redirect output to a log file so you can read it.

What happens to a job if the server is off at its scheduled time?

cron does not catch up. The run is simply skipped, because cron only starts jobs while it is running. For jobs that must not be missed, look at anacron or a systemd timer with Persistent=true.

Should I use my crontab or root's?

Run each job as the user with the least rights that can do it. Use sudo crontab -e only for tasks that really need root, such as system maintenance.

View MD Edit
Share
Helpful?
Progress is saved in this browser only.

Keep going: guides and tutorials

View MD Edit
Share
Helpful?
Run this on your own server

Levelrail deploys apps from git with health-checked releases and one-click rollback.

docker pull ghcr.io/glincker/levelrail:latest Install Levelrail From GLINR Studios