Cron Jobs Explained: Complete Guide for Developers (2026)
Cron jobs are the backbone of task automation in Unix-like systems. Whether you’re scheduling database backups, generating reports, cleaning up logs, or sending automated emails, understanding cron is essential for every developer and DevOps engineer. This comprehensive guide covers everything from basic syntax to advanced scheduling patterns, troubleshooting, and best practices for 2026.
1. What is a Cron Job?
A cron job is a scheduled task that runs automatically at specified times or intervals on Unix-like operating systems (Linux, macOS, BSD). The name “cron” comes from the Greek word “chronos” meaning time.
Why Cron Matters in 2026
Despite the rise of cloud-based schedulers and orchestration tools, cron remains the most widely used task scheduler because:
- Universal: Available on every Linux server, macOS machine, and WSL on Windows
- Lightweight: Minimal resource overhead compared to complex schedulers
- Reliable: Battle-tested for over 40 years with proven stability
- Simple: Easy to learn, no external dependencies required
- Flexible: Supports minute-level precision and complex schedules
Common Use Cases
| Use Case | Frequency | Example |
|---|---|---|
| Database Backups | Daily | Backup MySQL at 2 AM |
| Log Rotation | Daily/Weekly | Archive and compress logs |
| System Monitoring | Every 5 minutes | Check disk space, CPU usage |
| Report Generation | Weekly/Monthly | Generate sales reports every Monday |
| Data Synchronization | Hourly | Sync data between systems |
| Cache Clearing | Every 6 hours | Clear application cache |
2. Understanding Cron Syntax
Cron expressions consist of five time fields followed by the command to execute:
* * * * * 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)Field Values and Special Characters
| Character | Meaning | Example |
|---|---|---|
* | Any value | * * * * * = Every minute |
, | List of values | 0 9,17 * * * = 9 AM and 5 PM |
- | Range of values | 0 9-17 * * * = 9 AM to 5 PM |
/ | Step values | */15 * * * * = Every 15 minutes |
Quick Reference Examples
Every Minute
* * * * * /path/to/script.shEvery Hour
0 * * * * /path/to/script.shEvery Day at 2:30 AM
30 2 * * * /path/to/backup.shEvery Monday at 9 AM
0 9 * * 1 /path/to/weekly-report.sh3. Getting Started with Crontab
Essential Crontab Commands
# Edit your crontab
crontab -e
# List all cron jobs
crontab -l
# Remove all cron jobs
crontab -r
# Edit another user's crontab (requires sudo)
sudo crontab -u username -eStep-by-Step: Creating Your First Cron Job
Step 1: Create a Script
#!/bin/bash
# backup.sh - Simple backup script
echo "Backup started at $(date)" >> /var/log/backup.log
tar -czf /backups/backup-$(date +%Y%m%d).tar.gz /var/www/html
echo "Backup completed at $(date)" >> /var/log/backup.logStep 2: Make it Executable
chmod +x /path/to/backup.shStep 3: Add to Crontab
# Open crontab editor
crontab -e
# Add this line to run backup daily at 2 AM
0 2 * * * /path/to/backup.shStep 4: Verify
# List cron jobs to confirm
crontab -lpython script.py will fail. Use
/usr/bin/python3 /full/path/to/script.py instead.4. 50+ Real-World Cron Examples
System Maintenance
Clean Temp Files Daily
0 3 * * * find /tmp -type f -mtime +7 -deleteRuns at 3 AM daily, deletes files older than 7 days
Check Disk Space Every Hour
0 * * * * df -h | mail -s "Disk Space Report" admin@example.comRestart Service Weekly
0 4 * * 0 systemctl restart nginxRestarts Nginx every Sunday at 4 AM
Database Operations
MySQL Backup Daily at 2 AM
0 2 * * * mysqldump -u root -p'password' database > /backups/db-$(date +\%Y\%m\%d).sqlPostgreSQL Backup with Compression
0 2 * * * pg_dump -U postgres mydb | gzip > /backups/mydb-$(date +\%Y\%m\%d).sql.gzDelete Old Database Backups
0 5 * * * find /backups -name "*.sql" -mtime +30 -deleteKeeps only last 30 days of backups
Web Application Tasks
Clear Application Cache Every 6 Hours
0 */6 * * * php /var/www/artisan cache:clearGenerate Sitemap Daily
0 1 * * * /usr/bin/python3 /var/www/generate_sitemap.pySend Daily Email Reports
0 8 * * * /usr/bin/node /var/www/send-reports.jsSends reports every morning at 8 AM
Monitoring and Alerts
Check Website Uptime Every 5 Minutes
*/5 * * * * curl -f https://example.com || mail -s "Site Down!" admin@example.comMonitor SSL Certificate Expiry
0 9 * * 1 /usr/local/bin/check-ssl-expiry.shChecks every Monday at 9 AM
Data Processing
Process Log Files Hourly
0 * * * * /usr/bin/python3 /scripts/process-logs.pySync Files to S3 Every 30 Minutes
*/30 * * * * aws s3 sync /var/www/uploads s3://mybucket/uploadsGenerate Monthly Reports
0 0 1 * * /usr/bin/python3 /scripts/monthly-report.pyRuns on the 1st of every month at midnight
🚀 Build Cron Expressions Visually
Stop memorizing syntax! Our free Cron Job Builder lets you create expressions with a visual interface.
Try Cron Job Builder →5. Advanced Cron Techniques
Environment Variables in Cron
Cron jobs run with a minimal environment. Set variables at the top of your crontab:
SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=admin@example.com
# Now your cron jobs
0 2 * * * /path/to/backup.shRedirecting Output
# Discard all output (silent)
0 2 * * * /path/to/script.sh > /dev/null 2>&1
# Log output to file
0 2 * * * /path/to/script.sh >> /var/log/cron.log 2>&1
# Email output (default if MAILTO is set)
0 2 * * * /path/to/script.sh
# Separate stdout and stderr
0 2 * * * /path/to/script.sh >> /var/log/cron.log 2>> /var/log/cron-errors.logPreventing Overlapping Jobs
Use flock to prevent multiple instances:
*/5 * * * * flock -n /tmp/myjob.lock /path/to/script.shRunning Jobs at System Startup
@reboot /path/to/startup-script.shSpecial Time Strings
| String | Equivalent | Description |
|---|---|---|
@reboot | – | Run once at startup |
@yearly | 0 0 1 1 * | Once a year (Jan 1, midnight) |
@monthly | 0 0 1 * * | Once a month (1st, midnight) |
@weekly | 0 0 * * 0 | Once a week (Sunday, midnight) |
@daily | 0 0 * * * | Once a day (midnight) |
@hourly | 0 * * * * | Once an hour |
Using Special Strings
@daily /path/to/daily-backup.sh
@reboot /path/to/startup-script.sh
@hourly /path/to/hourly-check.sh6. Best Practices and Common Pitfalls
✅ Best Practices
1. Always Use Absolute Paths
# ❌ BAD: Relative paths
0 2 * * * python backup.py
# ✅ GOOD: Absolute paths
0 2 * * * /usr/bin/python3 /home/user/scripts/backup.py2. Add Comments to Your Crontab
# Database backup - runs daily at 2 AM
0 2 * * * /usr/local/bin/backup-db.sh
# Clear cache - runs every 6 hours
0 */6 * * * /usr/local/bin/clear-cache.sh3. Log Everything
#!/bin/bash
# backup.sh
LOG_FILE="/var/log/backup.log"
echo "=== Backup started at $(date) ===" >> "$LOG_FILE"
# Your backup logic here
if tar -czf /backups/backup-$(date +%Y%m%d).tar.gz /var/www/html; then
echo "SUCCESS: Backup completed" >> "$LOG_FILE"
else
echo "ERROR: Backup failed" >> "$LOG_FILE"
exit 1
fi
echo "=== Backup finished at $(date) ===" >> "$LOG_FILE"4. Handle Errors Gracefully
#!/bin/bash
set -e # Exit on error
set -u # Exit on undefined variable
set -o pipefail # Exit on pipe failure
# Your script logic here5. Test Before Scheduling
# Test your script manually first
/path/to/script.sh
# Then add to crontab
crontab -e❌ Common Pitfalls
7. Debugging and Troubleshooting
Why Isn’t My Cron Job Running?
1. Check if Cron Daemon is Running
# Check cron service status
systemctl status cron # Debian/Ubuntu
systemctl status crond # CentOS/RHEL
# Start cron if not running
sudo systemctl start cron2. Verify Cron Syntax
# List your crontab
crontab -l
# Use online validators or our Cron Job Builder
# https://toolshref.com/cron-job-builder-generate-linux-crontab-expressions/3. Check System Logs
# View cron logs
tail -f /var/log/syslog | grep CRON # Debian/Ubuntu
tail -f /var/log/cron # CentOS/RHEL
# Check for errors
grep CRON /var/log/syslog | grep error4. Test Script Permissions
# Check if script is executable
ls -l /path/to/script.sh
# Make executable if needed
chmod +x /path/to/script.sh5. Verify Environment Variables
# Add this to your crontab to debug environment
* * * * * env > /tmp/cron-env.txt
# Compare with your shell environment
env > /tmp/shell-env.txt
diff /tmp/cron-env.txt /tmp/shell-env.txtDebugging Checklist
| Check | Command | Expected Result |
|---|---|---|
| Cron daemon running | systemctl status cron | Active (running) |
| Crontab exists | crontab -l | Shows your jobs |
| Script executable | ls -l script.sh | -rwxr-xr-x |
| Script runs manually | /path/to/script.sh | No errors |
| Logs show execution | grep CRON /var/log/syslog | Shows job runs |
* * * * * echo "Cron is working at $(date)" >> /tmp/cron-test.txt8. Modern Alternatives to Cron
While cron is still widely used, modern alternatives offer additional features for complex scenarios:
Systemd Timers
Built into modern Linux distributions, systemd timers offer more features than cron:
- Better logging and monitoring
- Dependency management
- Calendar-based scheduling
- Persistent timers (run missed jobs after system boot)
Cloud-Based Schedulers
| Service | Best For | Pricing |
|---|---|---|
| AWS EventBridge | AWS infrastructure | Pay per event |
| Google Cloud Scheduler | GCP infrastructure | Free tier available |
| Azure Logic Apps | Azure infrastructure | Pay per execution |
| GitHub Actions | CI/CD workflows | Free for public repos |
When to Use Cron vs Alternatives
| Scenario | Recommendation | Reason |
|---|---|---|
| Simple server tasks | Cron | Lightweight, no dependencies |
| Complex workflows | Airflow, Prefect | Better dependency management |
| Cloud-native apps | Cloud schedulers | Better integration |
| Distributed systems | Kubernetes CronJobs | Container orchestration |
9. Essential Tools for Cron Development
Cron Expression Builders
- ToolsHref Cron Job Builder – Visual cron expression builder with validation and examples
- Crontab Guru – Popular online cron expression explainer
Monitoring and Alerting
- Cronitor – Monitor cron jobs and get alerts when they fail
- Healthchecks.io – Dead man’s switch for cron jobs
- UptimeRobot – Monitor cron-triggered endpoints
Related ToolsHref Tools
- Parse Apache/Nginx Timestamps – Process log files from cron jobs
- strftime Cheat Sheet – Format dates in your cron scripts
🛠️ Try Our Free Developer Tools
All tools run 100% in your browser. Your data never leaves your machine.
Explore All Tools →10. Frequently Asked Questions
Q: What is a cron job?
A: A cron job is a scheduled task that runs automatically at specified times or intervals on Unix-like operating systems (Linux, macOS). Cron jobs are defined using cron expressions in a crontab file and are commonly used for backups, log rotation, system maintenance, and automated reports.
Q: How do I create a cron job?
A: To create a cron job: 1) Open your crontab with crontab -e, 2)
Add a line with your cron expression and command (e.g.,
0 2 * * * /path/to/script.sh), 3) Save and exit. The cron daemon will automatically
pick up the changes and run your job at the specified time.
Q: What does * * * * * mean in cron?
A: The five asterisks (* * * * *) in cron syntax represent: minute
(0-59), hour (0-23), day of month (1-31), month (1-12), and day of week (0-7, where 0 and 7 are
Sunday). Five asterisks means “run every minute of every hour of every day”.
Q: How do I run a cron job every 5 minutes?
A: Use the expression */5 * * * * command. The */5 in
the minute field means “every 5 minutes”. This will run your command at :00, :05, :10, :15, :20,
:25, :30, :35, :40, :45, :50, and :55 minutes past each hour.
Q: Why is my cron job not running?
A: Common reasons: 1) Incorrect cron syntax – verify with
crontab -l, 2) Missing execute permissions on the script – use
chmod +x script.sh, 3) Wrong file paths – cron doesn’t use your shell environment,
always use absolute paths, 4) Cron daemon not running – check with
systemctl status cron, 5) Errors in the script itself – check
/var/log/syslog or /var/log/cron for error messages.
Q: How do I see cron job logs?
A: Check system logs: tail -f /var/log/syslog | grep CRON
(Debian/Ubuntu) or tail -f /var/log/cron (CentOS/RHEL). For script-specific logs,
redirect output in your crontab:
0 2 * * * /path/to/script.sh >> /var/log/myscript.log 2>&1
Q: Can I run cron jobs more frequently than every minute?
A: No, cron’s minimum interval is one minute. For sub-minute scheduling, use systemd timers, write a script with a sleep loop, or use a process supervisor like supervisord.
Q: How do I prevent multiple instances of a cron job from running?
A: Use flock to create a lock file:
*/5 * * * * flock -n /tmp/myjob.lock /path/to/script.sh. The -n flag
makes flock exit immediately if the lock is already held, preventing concurrent runs.
Conclusion
Cron jobs remain an essential tool for every developer and DevOps engineer in 2026. Despite the rise of cloud-based schedulers and orchestration platforms, cron’s simplicity, reliability, and universal availability make it the go-to choice for task automation.
Key Takeaways:
- Master the five-field cron syntax for precise scheduling
- Always use absolute paths in your cron jobs
- Implement proper logging and error handling
- Use flock to prevent concurrent job execution
- Monitor critical cron jobs with alerting tools
- Test scripts manually before adding to crontab
- Use our Cron Job Builder to avoid syntax errors
For more DevOps resources, check out our guides on parsing server logs and date formatting.
About the Author
ToolsHref Team consists of experienced DevOps engineers and system administrators who have managed thousands of cron jobs across production environments. We’ve debugged countless cron issues, optimized scheduling for high-traffic systems, and built automation pipelines for Fortune 500 companies. Our mission is to share practical, battle-tested knowledge with the developer community.
Expertise: Linux System Administration, DevOps, Automation, Cron, Systemd, Cloud Infrastructure
Experience: 15+ years managing production systems at scale
