Every system administrator and web developer deals with repetitive maintenance tasks: automated database backups, log rotation, dispatching queued emails, or polling external APIs. In Linux, task scheduling is managed natively by cron—a background daemon service that continuously monitors configuration tables and executes commands at predetermined intervals.
Crontab Schedule Syntax Breakdown
A crontab entry consists of five distinct time fields followed by the absolute system command to be executed.
| Field | Description | Allowed Range | Special Characters |
|---|---|---|---|
| 1st field | Minute | 0 – 59 | * (every), */5 (every 5th) |
| 2nd field | Hour | 0 – 23 | *, 2,4 (at 2 AM and 4 AM) |
| 3rd field | Day of Month | 1 – 31 | *, 1-15 (first half of month) |
| 4th field | Month | 1 – 12 | * |
| 5th field | Day of Week | 0 – 7 (0 and 7 represent Sunday) | 1-5 (Monday through Friday) |
Managing Crontab Schedules via CLI
Interact with user-specific crontab files using standard crontab utility flags.
- crontab -e: Opens the active user crontab inside the default text editor for modifications.
- crontab -l: Displays the full list of scheduled cron jobs for the current user.
- crontab -r: Removes all active scheduled jobs for the current user.
Practical Crontab Usage Examples
The snippet below illustrates common cron schedules used across web servers and automation scripts.
# 1. Execute a PHP maintenance worker every 15 minutes */15 * * * * /usr/bin/php /var/www/html/cron/sync.php > /dev/null 2>&1 # 2. Perform a daily database backup at 03:00 AM 0 3 * * * /usr/bin/mysqldump -u root -pPassword123 mydb > /backups/db_$(date +\%F).sql # 3. Purge application temp cache every Sunday at midnight 0 0 * * 0 /var/www/scripts/clear_cache.sh
Essential Cron Best Practices
Because cron runs within an isolated, stripped-down execution environment, always specify absolute paths for binaries and target scripts (e.g., /usr/bin/php instead of simply php). To capture troubleshooting outputs, redirect stdout and stderr into dedicated log files (e.g., >> /var/log/my_cron.log 2>&1).