Introduction to Cron Scheduling
In this tutorial, you will learn about Introduction to Cron Scheduling. We cover key concepts, practical examples, and best practices to help you master this topic.
Learn cron scheduling basics: what cron is, the five-field syntax, minute-hour-day-month-weekday format, and how cron enables automated time-based job execution.
What You Learn
You will learn what cron is, how the five-field syntax works, how to write your first crontab entry, and how cron differs from other scheduling approaches.
Why It Matters
Many backend tasks must run on a schedule: database backups at 3 AM, cache warming every hour, log rotation at midnight. Cron is the most widely used tool for these jobs. Understanding cron is essential for any backend developer.
Real-World Use
DodaTech uses cron for nighty database backups (0 3 * * *), malware signature updates every 2 hours (0 */2 * * *), weekly analytics reports (0 9 * * 1), and session cleanup every 6 hours (0 */6 * * *).
What is Cron?
Cron is a time-based job scheduler in Unix-like operating systems. It reads configuration files called crontabs and executes commands at specified times. The name comes from the Greek word "chronos" meaning time.
# Check if cron is running
systemctl status cron
# or
service cron status
# List current crontab entries
crontab -l
# Edit crontab
crontab -e
The Five-Field Syntax
A cron expression has five fields separated by spaces:
* * * * * command_to_execute
- - - - -
| | | | |
| | | | +---- Day of week (0-7, 0 and 7 = Sunday)
| | | +------ Month (1-12)
| | +-------- Day of month (1-31)
| +---------- Hour (0-23)
+------------ Minute (0-59)
# Run every minute
* * * * * /usr/bin/php /var/www/check.php
# Run every hour at minute 0
0 * * * * /usr/bin/python3 /opt/scripts/hourly.py
# Run daily at midnight
0 0 * * * /usr/local/bin/backup.sh
# Run every Monday at 9 AM
0 9 * * 1 /usr/bin/curl https://api.dodatech.com/reports/weekly
Special Characters in Cron
# Asterisk: matches any value
# */15 every 15 minutes
*/15 * * * * /opt/scripts/health_check.sh
# Comma: multiple values
# At 8 AM, 12 PM, and 5 PM
0 8,12,17 * * * /opt/scripts/report.sh
# Hyphen: range of values
# Every hour during business hours (9-17)
0 9-17 * * * /opt/scripts/business_hours.py
# Step: every N units
# Every 30 minutes
*/30 * * * * /opt/scripts/cache_warm.php
# Every 2 hours
0 */2 * * * /opt/scripts/maintenance.sh
Writing Your First Crontab
# Open the crontab editor
crontab -e
# Add your first entry (runs daily at 3 AM)
0 3 * * * /home/user/backup.sh
# Save and exit. Cron will automatically pick up changes.
# Verify with:
crontab -l
# Check that the job ran:
grep CRON /var/log/syslog | tail -5
Cron vs Other Schedulers
# Python schedule library (alternative to cron)
import schedule
import time
def backup():
print(f"Backup running at {time.strftime('%H:%M:%S')}")
def health_check():
print(f"Health check at {time.strftime('%H:%M:%S')}")
schedule.every().day.at("03:00").do(backup)
schedule.every(30).minutes.do(health_check)
schedule.every().monday.at("09:00").do(backup)
while True:
schedule.run_pending()
time.sleep(1)
Common Mistakes
1. Forgetting the Command Path
Cron runs with a minimal PATH. Always use full paths to commands and scripts, or set PATH at the top of the crontab.
2. Five Fields Required
A common mistake is writing 0 3 * * backup.sh with only four fields. Every cron expression must have exactly five time fields before the command.
3. Output Goes Nowhere
By default, cron output is emailed to the user. If mail is not configured, output is lost. Redirect output to a log file: 0 3 * * * backup.sh >> /var/log/backup.log 2>&1.
4. Scripts Not Executable
Cron runs scripts directly, not through a shell. Ensure scripts have execute permissions (chmod +x script.sh).
5. Environment Differences
Cron runs with a minimal environment. Scripts that work in your terminal may fail in cron due to missing environment variables.
Practice Questions
1. What does the cron expression 0 */2 * * * mean?
At minute 0 of every 2nd hour (runs at 00:00, 02:00, 04:00, etc.).
2. How many fields does a standard cron expression have?
Five fields: minute, hour, day of month, month, day of week.
3. What is the difference between cron and anacron?
Cron assumes the system runs continuously. Anacron can run missed jobs after system downtime.
4. How do you edit the current user's crontab?
Run crontab -e. This opens the crontab file in the default editor.
Challenge
Write crontab entries for: database backup every 6 hours, cache warming every 30 minutes during business hours (8 AM to 8 PM), weekly report every Monday at 9 AM, log rotation at midnight on the first day of each month.
FAQ
Mini Project: Daily Backup Crontab
# Set PATH for cron
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
# Log timestamp
0 3 * * * echo "Backup started at $(date)" >> /var/log/backup.log
# Database backup (daily at 3 AM)
0 3 * * * /usr/bin/mysqldump -u root mydb > /backups/mydb_$(date +\%Y\%m\%d).sql 2>> /var/log/backup.log
# File backup (daily at 3:30 AM)
30 3 * * * /usr/bin/rsync -a /home/user/data/ /backups/data/ >> /var/log/backup.log 2>&1
# Cleanup backups older than 30 days
0 4 * * * /usr/bin/find /backups/ -type f -mtime +30 -delete >> /var/log/backup.log 2>&1
# Test with:
# bash -x backup.sh
What's Next
Now that you understand cron basics, explore cron syntax deep dive for advanced expressions, then learn about special cron strings like @daily and @reboot.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro