NewCode CLOUD — 20% off your first month on all cloud VPSClaim

Cron Jobs on Linux: Schedule Backups, Scripts and Maintenance Tasks

Cron runs commands on a schedule: nightly database backups, log cleanup, certificate checks, sending a report every Monday. It has been part of Unix for decades and is installed on almost every Linux server. The syntax is short but easy to get wrong, and a cron job that fails silently can go unnoticed for months — usually until you need the backup it was supposed to make.

This guide explains the syntax, shows common schedules, and covers the habits that make cron jobs reliable.

Crontab syntax

Each line in a crontab 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 = Sunday)
│ │ │ │ │
* * * * *  command to run
Symbol Meaning Example
* every value * * * * * = every minute
, list 0 9,18 * * * = 09:00 and 18:00
- range 0 9-17 * * 1-5 = hourly, 9–17, Mon–Fri
/ step */15 * * * * = every 15 minutes

Common schedules

*/5 * * * *    every 5 minutes
0 * * * *      every hour, on the hour
30 2 * * *     every day at 02:30
0 3 * * 0      every Sunday at 03:00
0 4 1 * *      at 04:00 on the 1st of each month
0 0 1 1 *      once a year, 1 January
@reboot        once, when the server starts
@daily         same as 0 0 * * *

If you are unsure what a schedule means, paste it into a cron expression explainer before relying on it.

Editing your crontab

crontab -e            # edit the current user's jobs
crontab -l            # list them
sudo crontab -e       # root's jobs
sudo crontab -u deploy -l

The first time, crontab -e asks which editor to use; nano is the easiest.

System-wide cron files

Packages and administrators can also put jobs in:

  • /etc/crontab and /etc/cron.d/* — same syntax but with an extra user field after the five time fields.
  • /etc/cron.daily/, /etc/cron.weekly/, /etc/cron.monthly/ — executable scripts run at those intervals (no . in the file name, or they may be skipped on Debian/Ubuntu).

Example /etc/cron.d/backup:

30 2 * * * root /usr/local/bin/backup.sh >> /var/log/backup.log 2>&1

The five classic cron pitfalls

1. A minimal PATH

Cron runs with a very short PATH (often just /usr/bin:/bin). A command that works in your terminal may fail with “command not found”. Use absolute paths, or set PATH at the top of the crontab:

PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

Find a command’s full path with which mysqldump.

2. No environment

Cron does not load .bashrc or .profile, so variables, aliases and version managers (nvm, pyenv) are missing. Put what a job needs inside the script, or source an environment file explicitly.

3. The % character

In a crontab line, % means “new line” and must be escaped. This fails:

0 1 * * * tar czf /backup/site-$(date +%F).tar.gz /var/www

This works:

0 1 * * * tar czf /backup/site-$(date +\%F).tar.gz /var/www

Moving the command into a script avoids the problem entirely.

4. Time zones

Cron uses the server’s time zone. Check it with timedatectl. Many servers run in UTC, which avoids daylight-saving surprises; if your business runs on Hong Kong or Beijing time (UTC+8), remember that 02:00 UTC is 10:00 local time. To change it:

sudo timedatectl set-timezone Asia/Hong_Kong
sudo systemctl restart cron     # "crond" on AlmaLinux / Rocky

5. Silent failures

By default cron tries to email output to the user, and on most servers there is no mail system, so errors disappear. Always redirect output to a log:

30 2 * * * /usr/local/bin/backup.sh >> /var/log/backup.log 2>&1

2>&1 captures error messages too.

Write jobs as scripts

For anything longer than one command, write a script:

sudo nano /usr/local/bin/backup-db.sh
#!/usr/bin/env bash
set -euo pipefail                       # stop on any error

STAMP=$(date +%F_%H%M)
DEST=/var/backups/mysql
mkdir -p "$DEST"

mysqldump --single-transaction --all-databases | gzip > "$DEST/all-$STAMP.sql.gz"
find "$DEST" -name "*.sql.gz" -mtime +14 -delete   # keep 14 days

echo "$(date -Is) backup ok"
sudo chmod 750 /usr/local/bin/backup-db.sh
sudo /usr/local/bin/backup-db.sh        # run once by hand first

set -euo pipefail makes the script stop at the first error instead of carrying on and reporting success. More on database dumps in backing up MySQL and MariaDB.

Prevent overlapping runs

If a job sometimes takes longer than its interval, two copies can run at once and corrupt data. flock allows only one:

*/10 * * * * flock -n /run/lock/sync.lock /usr/local/bin/sync.sh >> /var/log/sync.log 2>&1

-n makes the second copy exit immediately instead of waiting.

Know when a job fails

A log file is only useful if someone reads it. Better options:

  • Heartbeat monitoring. Have the script call a URL at the end (curl -fsS https://monitor.example/ping/abc123). Services such as Healthchecks.io, or a push monitor in Uptime Kuma, alert you if the ping does not arrive on time.
  • Exit codes. With set -e, a failed step makes the script exit non-zero, so the heartbeat at the end is never sent.
  • Log rotation. Add /var/log/backup.log to logrotate so it does not grow forever:
/var/log/backup.log {
    weekly
    rotate 8
    compress
    missingok
}

Save it as /etc/logrotate.d/backup.

Checking that cron ran

grep CRON /var/log/syslog | tail          # Ubuntu / Debian
sudo journalctl -u cron --since today     # Ubuntu / Debian (systemd)
sudo journalctl -u crond --since today    # AlmaLinux / Rocky

These logs show that cron started the job, not that it succeeded — which is why the script’s own log and a heartbeat matter.

Cron or systemd timers?

cron systemd timer
Setup One line Two small files
Logging You must redirect Automatic, in journalctl
Runs missed jobs after downtime No (anacron aside) Yes, with Persistent=true
Resource limits and sandboxing No Yes
Randomised start time No RandomizedDelaySec=

For a quick job, cron is perfect. For important jobs on servers that are sometimes powered off, or jobs that need limits, use a timer — see systemd explained.

Useful examples

# Renew Let's Encrypt certificates (certbot usually installs its own timer — check first)
0 3 * * * certbot renew --quiet

# Run WordPress cron reliably instead of on page visits
*/5 * * * * cd /var/www/site && /usr/bin/php wp-cron.php > /dev/null 2>&1

# Weekly security scan
0 4 * * 0 /usr/bin/clamscan -ri /var/www >> /var/log/clamscan.log 2>&1

# Clear a cache folder daily
15 1 * * * find /var/www/site/cache -type f -mtime +1 -delete

Checklist

  • Script runs correctly when started by hand
  • Absolute paths, % escaped or moved into a script
  • Output redirected with >> logfile 2>&1
  • Time zone confirmed with timedatectl
  • flock for jobs that might overlap
  • Heartbeat or alert so failures are noticed