Intermediate · 10 min · practise every command in the built-in terminal

cron — Task Scheduler

cron runs commands automatically on a schedule.

Edit crontab

crontab -e      # Edit your crontab
crontab -l      # List your crontab
crontab -r      # Remove your crontab

Crontab syntax

* * * * * command
│ │ │ │ │
│ │ │ │ └── Day of week (0-7, 0 and 7 = Sunday)
│ │ │ └──── Month (1-12)
│ │ └────── Day of month (1-31)
│ └──────── Hour (0-23)
└────────── Minute (0-59)

Examples

# Every minute
* * * * * /path/to/script.sh

# Every hour at minute 0
0 * * * * /backup.sh

# Every day at 2:30 AM
30 2 * * * /daily-backup.sh

# Every Monday at 9 AM
0 9 * * 1 /weekly-report.sh

# Every 5 minutes
*/5 * * * * /check.sh

# At 6 AM and 6 PM
0 6,18 * * * /twice-daily.sh

# First day of every month
0 0 1 * * /monthly.sh

Special strings

@reboot    command    # Run at startup
@hourly    command    # = 0 * * * *
@daily     command    # = 0 0 * * *
@weekly    command    # = 0 0 * * 0
@monthly   command    # = 0 0 1 * *

Best practices

# Redirect output to log:
30 2 * * * /backup.sh >> /var/log/backup.log 2>&1

# Use full paths (cron has minimal PATH):
0 * * * * /usr/bin/python3 /home/student/script.py

# Set PATH in crontab:
PATH=/usr/local/bin:/usr/bin:/bin

Practice tasks

  1. View your current crontab
  2. Open your crontab for editing and add a scheduled task
  3. Remove your crontab entirely

Commands in this lesson

Advanced Commands