Scheduling with cron
cron runs commands automatically on a schedule you define.
Syntax
minute hour day month weekday commandcron is the built-in scheduler. You list jobs in a crontab, and cron runs them at the times you specify — perfect for backups, cleanups and reports.
Editing your schedule
crontab -e opens your personal crontab. Each line is one job: five time fields followed by the command.
┌ minute (0-59)
│ ┌ hour (0-23)
│ │ ┌ day of month (1-31)
│ │ │ ┌ month (1-12)
│ │ │ │ ┌ day of week (0-6, Sun=0)
* * * * * commandA * means "every". So 0 2 * * * means 2:00 AM every day.
Example
# Edit your personal schedule
crontab -e
# List your scheduled jobs
crontab -l
# Example crontab lines:
# Run a backup every day at 2:00 AM
0 2 * * * /home/alice/backup.sh
# Clear temp files every Sunday at midnight
0 0 * * 0 rm -rf /home/alice/tmp/*
# Every 15 minutes
*/15 * * * * /home/alice/check.shWhen to use it
- A sysadmin schedules a database backup every night at 2 AM with '0 2 * * * /opt/scripts/backup_db.sh >> /var/log/backup.log 2>&1'.
- A developer clears a temp directory every Monday at 6 AM: '0 6 * * 1 rm -rf /tmp/app_cache/*'.
- A monitoring script emails a weekly disk usage report every Sunday at midnight using a cron job that pipes 'df -h' to 'mail'.
More examples
Edit and add a cron job
Shows how to edit crontab, the five time fields, and redirecting both stdout and stderr to a log file.
# Open the user's crontab
crontab -e
# Format: minute hour day month weekday command
# m h dom mon dow command
0 2 * * * /opt/scripts/backup.sh >> /var/log/backup.log 2>&1
# List current crontab
crontab -lCommon cron schedule patterns
Demonstrates four common cron schedule patterns: interval, daily, weekly, and monthly.
# Every 5 minutes
*/5 * * * * /opt/scripts/health_check.sh
# Every day at midnight
0 0 * * * /opt/scripts/daily_report.sh
# Every Monday at 6 AM
0 6 * * 1 /opt/scripts/weekly_cleanup.sh
# First day of every month at 3 AM
0 3 1 * * /opt/scripts/monthly_billing.shSystem-wide cron with /etc/cron.d
Shows /etc/cron.d format which adds a username field and allows setting PATH for the cron environment.
# /etc/cron.d/myapp (system-wide cron file)
# Has an extra 'user' field before the command
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin
# Run as 'deploy' user every night at 1 AM
0 1 * * * deploy /opt/myapp/scripts/cleanup.sh
Discussion