Cron Jobs: Automated Tasks
Cron jobs allow you to execute commands or scripts automatically based on a defined schedule. They are used for backups, cleanup, updates, sending emails and much more.
Modify the crontab
Each user has their own crontab. To modify it:
crontab -e
The first time it will ask which editor to use (choose nano if unsure).
To view active cron jobs:
crontab -l
To delete all cron jobs:
crontab -r
Crontab syntax
# ┌───────── minute (0-59)
# │ ┌───────── hour (0-23)
# │ │ ┌───────── day of month (1-31)
# │ │ │ ┌───────── month (1-12)
# │ │ │ │ ┌───────── day of week (0=Sunday, 6=Saturday)
# │ │ │ │ │
# * * * * * command
Practical examples
# Every minute
# Every hour (at minute 0)
0 * * * * /path/script.sh
# Every day at 03:00
0 3 * * * /path/script.sh
# Every Monday at 08:30
30 8 * * 1 /path/script.sh
# First of the month at midnight
0 0 1 * * /path/script.sh
# Every 5 minutes
*/5 * * * * /path/script.sh
# Every 6 hours
0 */6 * * * /path/script.sh
# Monday-Friday at 09:00
0 9 * * 1-5 /path/script.sh
- /path/script.sh
Real-world usage examples
Database backup every night at 02:00
0 2 * * * mysqldump -u root -pPASSWORD database > /backups/db_$(date +\%Y\%m\%d).sql
Clean up logs every Sunday
0 4 * * 0 journalctl --vacuum-time=30d
Automatic SSL renewal
0 3 * * * certbot renew --quiet
Synchronize with rsync every hour
0 * * * * rsync -az /var/www/ backup@IP_BACKUP:/backups/www/
Automatically restart a service if down
*/5 * * * * systemctl is-active --quiet nginx || systemctl restart nginx
Save the output of cron jobs
By default cron job output is sent via email to the system user. To save it to a file:
# Save stdout and stderr to file
0 3 * * * /path/script.sh >> /var/log/my-cron.log 2>&1
# Discard all output
0 3 * * * /path/script.sh > /dev/null 2>&1
System crontab
Besides user crontab, you can use files in /etc/cron.d/ or these directories:
Just put an executable script in these directories:
nano /etc/cron.daily/my-backup
chmod +x /etc/cron.daily/my-backup
- /etc/cron.hourly/: scripts run every hour
- /etc/cron.daily/: scripts run every day
- /etc/cron.weekly/: scripts run every week
- /etc/cron.monthly/: scripts run every month
Verify that cron works
# See cron logs (Debian/Ubuntu)
grep CRON /var/log/syslog | tail -20
# With journald
journalctl -u cron -n 20
# Verify the service is active
systemctl status cron # Debian/Ubuntu
systemctl status crond # CentOS/AlmaLinux
Online tool to generate cron
If you don't remember the syntax, use crontab.guru to generate and verify cron expressions visually.
Verwandte Artikel
Package Installation
How to install, update and remove software on your Linux server
Web Server: Nginx
Installation and basic configuration of Nginx on your server
Web Server: Apache
Installation and basic configuration of Apache on your server
