Linux Cron Jobs: A Complete Guide to Task Scheduling

What Cron Is and How It Works

Cron is a daemon that wakes up every minute, reads crontab files, and runs any commands whose time specification matches the current time. It runs as a system service (crond on RHEL, cron on Debian) and starts automatically at boot.

There are two types of crontab:

---

Cron Syntax

MIN  HOUR  DOM  MON  DOW  COMMAND
  *     *    *    *    *  /path/to/script.sh

Common patterns:

# Every day at 2:30 AM
30 2 * * * /opt/scripts/backup.sh

# Every 15 minutes
*/15 * * * * /opt/scripts/healthcheck.sh

# Every Monday at 9 AM
0 9 * * 1 /opt/scripts/weekly-report.sh

# First day of each month
0 0 1 * * /opt/scripts/monthly-cleanup.sh

---

The Most Common Failure: PATH

Cron runs with a stripped-down environment. Commands that work in your shell fail silently in cron because /usr/local/bin and other custom paths are not in cron's PATH.

Fix: always use absolute paths in cron jobs.

# Wrong
30 2 * * * backup.sh

# Right
30 2 * * * /opt/scripts/backup.sh

Check what environment cron actually has:

* * * * * env > /tmp/cron-env.txt

---

Capturing Output

# Capture stdout and stderr to a log file
30 2 * * * /opt/scripts/backup.sh >> /var/log/backup.log 2>&1

# Suppress all output
30 2 * * * /opt/scripts/backup.sh > /dev/null 2>&1

Note: unescaped % in cron is treated as a newline character — escape it as \%.

---

Debugging a Silent Failure

# Check cron is running
systemctl status cron
journalctl -u cron --since "1 hour ago"

# Verify the crontab
crontab -l

# Test as the cron user
sudo -u www-data bash -c '/opt/scripts/backup.sh'

Other common causes: script not executable (chmod +x), Windows line endings (dos2unix), wrong time zone, no trailing newline in the crontab file.

---

System-Wide Cron

/etc/cron.d/ files include a username field:

# /etc/cron.d/myapp
30 2 * * * root /opt/myapp/backup.sh >> /var/log/myapp-backup.log 2>&1

Practice scheduling in the ShellGenius Linux Labs — the cron-jobs challenge has a real broken cron setup to debug and fix.