Salta ai contenuti

Cron

Cron is a time-based task scheduler in Unix/Linux systems. Schedule recurring jobs with crontab or system cron files.

Cron Syntax

┌───────────── minute (0 - 59)
│ ┌───────────── hour (0 - 23)
│ │ ┌───────────── day of month (1 - 31)
│ │ │ ┌───────────── month (1 - 12)
│ │ │ │ ┌───────────── day of week (0 - 6) (Sunday is 0)
│ │ │ │ │
│ │ │ │ │
* * * * * command_to_run

Special Syntax

ExpressionDescriptionEquivalent
@yearlyOnce per year on January 1st0 0 1 1 *
@annuallySame as @yearly0 0 1 1 *
@monthlyOnce per month on 1st0 0 1 * *
@weeklyOnce per week on Sunday0 0 * * 0
@dailyOnce per day at midnight0 0 * * *
@midnightSame as @daily0 0 * * *
@hourlyOnce per hour at minute 00 * * * *
@rebootRun once at startupSpecial

Common Examples

PatternDescription
0 0 * * *Daily at midnight
0 12 * * *Daily at noon
0 9 * * 1-5Weekdays (Mon-Fri) at 9 AM
0 9 * * 0,6Weekends (Sat-Sun) at 9 AM
*/15 * * * *Every 15 minutes
0 */6 * * *Every 6 hours
0 0 1 * *First day of month at midnight
0 0 1 1 *January 1st at midnight (New Year)
30 2 * * *Daily at 2:30 AM
0 22 * * 1-5Weekdays at 10 PM

Minute & Hour Patterns

# Every minute
* * * * *

# Every 5 minutes
*/5 * * * *

# Every 30 minutes
*/30 * * * *

# Every hour
0 * * * *

# Every 4 hours
0 */4 * * *

# Every 2 hours, Monday-Friday
0 */2 * * 1-5

# 9 AM - 5 PM every hour, weekdays
0 9-17 * * 1-5

Day & Date Patterns

# Every day
0 0 * * *

# Every other day
0 0 */2 * *

# 1st and 15th of month
0 0 1,15 * *

# Last day of month (approximation)
0 0 28-31 * *

# Every Sunday
0 0 * * 0

# Every Monday
0 0 * * 1

# Monday and Friday
0 0 * * 1,5

# Weekdays only (Monday-Friday)
0 0 * * 1-5

# Weekends (Saturday-Sunday)
0 0 * * 0,6

Real-World Examples

Backups

# Daily backup at 2 AM
0 2 * * * /home/user/backup.sh

# Weekly backup on Sunday at 3 AM
0 3 * * 0 /usr/local/bin/weekly-backup.sh

# Monthly backup on 1st at 1 AM
0 1 1 * * tar czf /backups/monthly-$(date +%Y%m%d).tar.gz /important/data

Maintenance Tasks

# Clear cache every day at 1 AM
0 1 * * * rm -rf /var/cache/app/*

# Log rotation every Sunday at 4 AM
0 4 * * 0 /usr/sbin/logrotate /etc/logrotate.conf

# Database optimization first Tuesday at 2 AM
0 2 * * 2 /usr/bin/mysqlcheck -Aao

Monitoring & Alerts

# Check disk space every 6 hours
0 */6 * * * /usr/local/bin/check-disk-space.sh

# Send health report daily at 9 AM
0 9 * * * /opt/monitoring/health-report.sh | mail -s "Daily Report" admin@example.com

# Verify SSL certificates expiry weekly
0 10 * * 1 /usr/local/bin/check-ssl-certs.sh

Data Processing

# Process daily logs at 1 AM
0 1 * * * /opt/scripts/process-logs.py

# Generate reports every Monday at 8 AM
0 8 * * 1 /usr/local/bin/generate-reports.sh

# Sync data every 30 minutes
*/30 * * * * /home/user/sync-data.sh

Cron Environment

Variables available in cron jobs:

SHELL=/bin/bash
PATH=/usr/bin:/bin
MAILTO=admin@example.com
HOME=/home/user

# Set in crontab before jobs
SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin
MAILTO=alerts@example.com

# Then define jobs
0 9 * * * /usr/local/bin/backup.sh

Logging & Redirection

# Log output to file
0 9 * * * /backup.sh >> /var/log/backup.log 2>&1

# Log to syslog
0 9 * * * /usr/local/bin/task.sh 2>&1 | logger -t mytask

# Append to log with timestamp
0 9 * * * echo "$(date): Running task" >> /var/log/task.log && /task.sh

# Suppress output
0 9 * * * /backup.sh > /dev/null 2>&1

# Email output if command fails
0 9 * * * /backup.sh || echo "Backup failed" | mail admin@example.com

System Cron Files

Location of system-wide cron jobs:

/etc/cron.d/          # System cron jobs (run as specified user)
/etc/cron.daily/      # Scripts run daily by run-parts
/etc/cron.hourly/     # Scripts run hourly
/etc/cron.weekly/     # Scripts run weekly
/etc/cron.monthly/    # Scripts run monthly

System Cron Format

# /etc/cron.d/example
# Format: minute hour day month weekday user command

# Run daily backup as root
0 2 * * * root /usr/local/bin/backup.sh

# Run hourly check as www-data user
0 * * * * www-data /usr/local/bin/health-check.sh

# Run weekly report as reports user
0 3 * * 0 reports /opt/reports/generate.sh

@reboot (Startup)

# Run script once at system startup
@reboot /usr/local/bin/startup.sh

# Delay before running at startup
@reboot sleep 60 && /usr/local/bin/delayed-start.sh

# Start service on reboot with logging
@reboot /etc/init.d/myservice start >> /var/log/startup.log 2>&1

Troubleshooting

Check Cron Status

# Service status (systemd systems)
systemctl status cron

# Service status (older systems)
service cron status

# Start cron service
sudo systemctl start cron

# Enable cron on boot
sudo systemctl enable cron

View Cron Logs

# Ubuntu/Debian
sudo tail -f /var/log/syslog | grep CRON

# CentOS/RHEL
sudo tail -f /var/log/cron

# Using journalctl (newer systems)
journalctl -u cron -f

# Search for specific cron job
grep CRON /var/log/syslog | grep "myjob"

Debug Cron Issues

# Run cron job manually to test
bash /home/user/script.sh

# Check script permissions (must be executable)
chmod +x /home/user/script.sh

# Verify crontab syntax
crontab -l

# Test environment variables
env > /tmp/cron-env.log

# Add verbose logging in script
#!/bin/bash
echo "$(date): Job started" >> /var/log/myjob.log
# ... rest of script

Best Practices

  • Always use absolute paths in cron jobs
  • Redirect output to log files for debugging
  • Use meaningful MAILTO variable for alerts
  • Test scripts manually before adding to cron
  • Use specific times to avoid resource conflicts
  • Add comments in crontab for clarity
  • Monitor cron logs regularly
  • Use version control for cron configurations
  • Document why each job exists
  • Include error handling in scripts

Resources


Last updated: 2026-03-30