Scheduling Recurring Tasks in CentOS with Cron
CentOS supports automated recurring task execution through the cron daemon, a time-based job scheduler that runs commands or scripts at predefined intervals.
Common Use Cases
-
System hygiene: Rotating or purging log files, cleraing temporary directories, verifying disk space.
-
Data protection: Executing periodic database dumps, syncing critical directories via
rsync, or triggering full system snapshots. -
Workflow automation: Launching ETL pipelines, refreshing cache layers, or polling external APIs for status updates.
-
Operational notfiications: Sending health reports via email or webhook when thresholds are exceeded.
How Cron Works
The crond service reads schedule definitions from multiple locations:
- Per-user crontabs stored in
/var/spool/cron/(edited viacrontab -e). - System-wide configuration in
/etc/crontab, which includes an additional user field. - Drop-in files under
/etc/cron.d/, each treated as a separate crontab with full syntax support.
Each line in a crontab follows this structure:
MIN HOUR DOM MON DOW COMMAND
Where:
MIN: 0–59HOUR: 0–23DOM: Day of month, 1–31MON: Month, 1–12 or names likejan,febDOW: Day of week, 0–7 (both 0 and 7 represent Sunday) or names likemon,tue
Special characters include * (any value), , (list), - (range), and / (step values).
Setting Up a Scheduled Job
To schedule a task for the current user:
# Open the user's crontab in the default editor
crontab -e
Add a line such as:
0 2 * * 0 /usr/local/bin/weekly-backup.sh >> /var/log/backup.log 2>&1
This runs /usr/local/bin/weekly-backup.sh at 2:00 AM every Sunday.
For system-level jobs requiring root privileges, avoid editing /etc/crontab directly unless necessary. Instead, place a file in /etc/cron.d/ with proper permissions (e.g., 0644) and include the username before the command:
# /etc/cron.d/disk-check
0 6 * * * root /usr/local/sbin/check-disk-usage.sh
Ensure scripts have execute permissions (chmod +x) and use absolute paths for binaries and files.
Verify active schedules with:
crontab -l # current user
sudo crontab -u root -l # root's crontab
sudo systemctl status crond # confirm service is running
Cron logs are typically found in /var/log/cron. Enable verbose logging by adjusting /etc/rsyslog.conf if deeper debugging is required.