30. Cron Job Scheduling
In Linux, the foundational tool for time-based job scheduling is Cron.
30.1 Cron Fundamentals
Section titled “30.1 Cron Fundamentals”What is Cron?
Section titled “What is Cron?”Cron is a time-based job scheduler in Unix-like operating systems. Users and administrators configure commands or shell scripts to run automatically at specific dates, times, or recurring intervals.
The Cron Daemon (cron / crond)
Section titled “The Cron Daemon (cron / crond)”The scheduler runs as a persistent background daemon:
- On Debian/Ubuntu:
cron.service - On RHEL/AlmaLinux/Rocky:
crond.service
The daemon wakes up every single minute (at :00 seconds), inspects scheduled job tables, checks if any job’s timestamp matches the current system time, executes eligible jobs in the background, and goes back to sleep.
# Check if the cron daemon is runningsudo systemctl status cron # or crond on RHELCron vs Manually Executed Commands
Section titled “Cron vs Manually Executed Commands”| Aspect | Manual Terminal Execution | Cron Execution |
||||
| Environment | Inherits user’s full shell environment, $PATH, aliases | Minimal default environment (/usr/bin:/bin), no interactive profile |
| Working Directory | Current working directory | User’s $HOME directory |
| Standard Output (stdout) | Printed directly to terminal screen | Discarded or emailed to local mail spool unless explicitly redirected |
| Interactive Prompts | Supports user input (read, [y/N] prompts) | Fails immediately if a command waits for interactive user input |
Common Production Use Cases
Section titled “Common Production Use Cases”- Daily/weekly compressed database backups and cloud sync.
- Log pruning and log rotation.
- Renewal of Let’s Encrypt SSL/TLS certificates via Certbot (
certbot renew). - Health checks and watchdog monitoring scripts.
- Periodic system updates (
apt updateor security scans).
30.2 Managing Crontabs (crontab Command)
Section titled “30.2 Managing Crontabs (crontab Command)”Each user on a Linux system (including root) has their own private cron table called a Crontab. Individual user crontab files are stored in /var/spool/cron/crontabs/ (Debian/Ubuntu) or /var/spool/cron/ (RHEL), but they should never be edited directly by hand.
Use the crontab CLI tool:
# Edit the current user's crontab (opens in default editor: nano/vi)crontab -e
# List the current user's active cron jobscrontab -l
# Remove/delete all cron jobs for the current user (Use with caution!)crontab -r
# As root: Edit another user's crontab (e.g. for the 'nginx' or 'deploy' service user)sudo crontab -u deploy -e
# As root: View another user's crontabsudo crontab -u deploy -l30.3 Cron Syntax & Timing Expressions
Section titled “30.3 Cron Syntax & Timing Expressions”A crontab entry consists of five time/date fields followed by the command to execute:
┌───────────── Minute (0 - 59) │ ┌─────────── Hour (0 - 23, 24-hour clock) │ │ ┌───────── Day of month (1 - 31) │ │ │ ┌─────── Month (1 - 12 or JAN - DEC) │ │ │ │ ┌───── Day of week (0 - 6, Sunday = 0 or 7, or SUN - SAT) │ │ │ │ │ * * * * * /path/to/command argument1 argument2Special Operators
Section titled “Special Operators”*(Asterisk / Wildcard): Matches every possible value for that field (e.g.,*in the hour field means “every hour”).,(Comma / Value List): Specifies multiple discrete values (e.g.,1,15,30in the minute field).-(Hyphen / Range): Specifies an inclusive range of values (e.g.,1-5in the day-of-week field means Monday through Friday)./(Slash / Step Intervals): Skips values in steps (e.g.,*/15in the minute field means “every 15 minutes”,*/2in hours means “every 2 hours”).
Real-World Timing Examples
Section titled “Real-World Timing Examples”# Run every minute of every day* * * * * /opt/scripts/heartbeat.sh
# Run every 15 minutes*/15 * * * * /opt/scripts/check_queue.sh
# Run at 02:00 AM every night0 2 * * * /opt/scripts/db_backup.sh
# Run at 04:30 AM every Monday through Friday30 4 * * 1-5 /opt/scripts/weekday_report.sh
# Run at midnight on the 1st of every month0 0 1 * * /opt/scripts/monthly_billing.sh
# Run at 03:00 AM every Sunday (0 = Sunday)0 3 * * 0 /opt/scripts/full_system_backup.sh
# Run at 00:00, 06:00, 12:00, and 18:00 every day (every 6 hours)0 0,6,12,18 * * * /opt/scripts/cert_check.sh# (or using step notation):0 */6 * * * /opt/scripts/cert_check.shCron Shortcuts (Special Strings)
Section titled “Cron Shortcuts (Special Strings)”Instead of 5 asterisks, cron supports predefined shortcut macros:
| Shortcut | Equivalent Expression | Meaning |
||||
| @reboot | Run once at system startup | Perfect for starting background processes after boot |
| @yearly / @annually| 0 0 1 1 * | Run once a year at midnight on January 1st |
| @monthly | 0 0 1 * * | Run once a month at midnight on the first day |
| @weekly | 0 0 * * 0 | Run once a week at midnight on Sunday |
| @daily / @midnight | 0 0 * * * | Run once a day at midnight |
| @hourly | 0 * * * * | Run once an hour at the start of the hour |
Example:
@reboot /opt/app/start_service.sh@daily /opt/scripts/cleanup_tmp.sh30.4 System-Wide Cron Directories
Section titled “30.4 System-Wide Cron Directories”Beyond individual user crontabs, Linux provides system-wide directories for administrative automation.
1. /etc/crontab
Section titled “1. /etc/crontab”The system-wide crontab file. Unlike user crontabs, it includes a mandatory User field between the timing expression and the command:
# m h dom mon dow user command0 2 * * * root /usr/local/sbin/backup_all.sh2. /etc/cron.d/
Section titled “2. /etc/cron.d/”A modular directory where packages (like certbot, sysstat, or custom services) drop their own crontab files.
- Files here use the same syntax as
/etc/crontab(they must specify the username). - Modular files make software installation and removal clean without editing a single shared file.
3. Periodic Schedule Directories
Section titled “3. Periodic Schedule Directories”Instead of writing timing expressions, you can simply drop executable shell scripts directly into these directories:
/etc/cron.hourly/: Scripts run every hour./etc/cron.daily/: Scripts run once a day (typically around 6:00 AM viaanacron)./etc/cron.weekly/: Scripts run once a week./etc/cron.monthly/: Scripts run once a month.
[!IMPORTANT] Scripts placed in
/etc/cron.daily/and similar folders must be executable (chmod +x), must include a proper shebang (#!/usr/bin/env bash), and should not have file extensions like.sh(Debian’srun-partstool will ignore filenames with dots!).
30.5 The Cron Environment Trap
Section titled “30.5 The Cron Environment Trap”The single most common reason why a script “works in my terminal but fails in cron” is the Environment.
1. Minimal $PATH
Section titled “1. Minimal $PATH”In your interactive shell, $PATH includes /usr/local/bin, /home/user/.cargo/bin, /snap/bin, etc.
In cron, $PATH is typically restricted to just /usr/bin:/bin. If your script calls docker, aws, node, or a script in /usr/local/bin, cron will fail with command not found.
Solutions:
- Always use absolute paths to all executables in scripts and crontabs:
Terminal window # BAD:python3 backup.py# GOOD:/usr/bin/python3 /opt/scripts/backup.py - Or explicitly define
$PATHat the very top of your crontab:SHELL=/bin/bashPATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/binHOME=/root0 2 * * * /opt/scripts/backup.sh
2. Working Directory
Section titled “2. Working Directory”Cron executes commands in the user’s home directory. If your script relies on relative paths (e.g. ./config.json), it will fail unless the script explicitly cds to its directory:
0 3 * * * cd /opt/my-app && ./run_job.sh30.6 Cron Logging & Troubleshooting
Section titled “30.6 Cron Logging & Troubleshooting”Because cron jobs run disconnected from any terminal, standard output (stdout) and error output (stderr) have nowhere to display.
1. Redirecting Output
Section titled “1. Redirecting Output”Always redirect both stdout and stderr to a log file:
# Append both stdout (1) and stderr (2) to a log file:0 2 * * * /opt/scripts/backup.sh >> /var/log/backup.log 2>&1
# Suppress all output completely (discard to /dev/null):0 2 * * * /opt/scripts/backup.sh > /dev/null 2>&12. Inspecting Cron Logs
Section titled “2. Inspecting Cron Logs”When troubleshooting whether a job actually executed:
- Ubuntu / Debian:
Terminal window # Filter syslog for cron eventssudo grep CRON /var/log/syslog# or using journalctlsudo journalctl -u cron -f - RHEL / Rocky / AlmaLinux:
Terminal window # Dedicated cron log filesudo tail -f /var/log/cron
3. Testing the Cron Environment Manually
Section titled “3. Testing the Cron Environment Manually”To simulate the exact stripped-down environment that cron will experience, run your script using env -i:
env -i HOME=/root PATH=/usr/bin:/bin /opt/scripts/backup.shIf the script fails here, you have missing environment variables or non-absolute paths!
30.7 Cron Security & Hardening
Section titled “30.7 Cron Security & Hardening”Cron runs with the full privileges of the user that owns the crontab. Securing cron is vital to preventing privilege escalation.
1. Restricting Access: /etc/cron.allow & /etc/cron.deny
Section titled “1. Restricting Access: /etc/cron.allow & /etc/cron.deny”Administrators can control which users are permitted to create cron jobs:
- If
/etc/cron.allowexists, only users listed in this file can usecrontab. - If
/etc/cron.allowdoes NOT exist, everyone can usecrontabexcept users listed in/etc/cron.deny. - Hardening Best Practice: Create an
/etc/cron.allowcontaining onlyrootand authorized administrative users:Terminal window sudo echo "root" > /etc/cron.allowsudo echo "deploy" >> /etc/cron.allow
2. Protecting Script Permissions
Section titled “2. Protecting Script Permissions”If a cron job runs as root, the script it executes must be strictly write-protected. If a standard user can edit /opt/scripts/backup.sh, they can add a command to grant themselves root access:
# Ensure root owns the script and only root can write to itsudo chown root:root /opt/scripts/backup.shsudo chmod 700 /opt/scripts/backup.sh3. Never Store Secrets in Crontab
Section titled “3. Never Store Secrets in Crontab”Avoid passing passwords or API tokens directly as CLI arguments in crontab (e.g. mysqldump -pSecretPassword). Any user on the system can see command arguments by running ps aux! Instead, store credentials in a root-readable config file (like ~/.my.cnf with chmod 600).
4. Detecting Malicious / Persistence Cron Jobs
Section titled “4. Detecting Malicious / Persistence Cron Jobs”Attackers and rootkits frequently establish persistence by injecting jobs into crontab:
# Audit all user crontabs on the systemfor user in $(cut -f1 -d: /etc/passwd); do crontab -u "$user" -l 2>/dev/null && echo "=== Crontab for $user ==="done
# Inspect system-wide cron foldersls -la /etc/cron* /etc/cron.d/