Automation
Schedule recurring tasks with cron and understand crontab syntax and management.
Crontab Syntax
# Minute Hour Day-of-Month Month Day-of-Week Command
# 0-59 0-23 1-31 1-12 0-6 (Sun=0)
* * * * * /path/to/command
Common shortcuts: @reboot, @daily, @weekly, @monthly, @hourly
Manage Your Crontab
# Edit your cron jobs
crontab -e
# List your cron jobs
crontab -l
# Remove all your cron jobs
crontab -r
# Edit another user's crontab (as root)
crontab -u www-data -e
Common Examples
# Run backup daily at 2:30 AM
30 2 * * * /home/craig/scripts/backup.sh >> /var/log/backup.log 2>&1
# Clear temp files every Sunday at midnight
0 0 * * 0 find /tmp -type f -atime +7 -delete
# Renew SSL cert twice daily (certbot)
0 */12 * * * certbot renew --quiet
# Send a heartbeat every 5 minutes
*/5 * * * * curl -s https://hc-ping.com/your-uuid > /dev/null
# Run a Python script at 9 AM on weekdays
0 9 * * 1-5 /usr/bin/python3 /home/craig/scripts/report.py
# Run on the 1st of every month
0 6 1 * * /home/craig/scripts/monthly_report.sh
System Cron Directories
# Drop scripts into these directories:
/etc/cron.hourly/ # runs every hour
/etc/cron.daily/ # runs daily
/etc/cron.weekly/ # runs weekly
/etc/cron.monthly/ # runs monthly
# System-wide crontab
sudo nano /etc/crontab
Debug Cron Jobs
# Log all cron activity
grep CRON /var/log/syslog
# Redirect output in the cron job itself
0 3 * * * /path/to/script.sh >> /var/log/myjob.log 2>&1
# Test the script manually with the same environment
env -i /bin/bash -c 'export HOME=/root; /path/to/script.sh'