What is crontab
cron is the Linux scheduler. A crontab ("cron table") is the list of jobs that run at the times you set.
Common uses:
- Backups.
- Maintenance scripts.
- Cleaning temporary files.
- Updating programs.
- Automatic reports.
The crontab commands
Edit your crontab:
crontab -e
List the jobs:
crontab -l
Remove all your jobs:
crontab -r
Warning:
crontab -r deletes the whole file at once with no question. Back up with crontab -l > cron.bak first.Edit the crontab of another user (as root):
sudo crontab -u username -e
Cron syntax
* * * * * command
The five fields are:
| Field | Values |
|---|---|
| Minute | 0-59 |
| Hour | 0-23 |
| Day of month | 1-31 |
| Month | 1-12 |
| Day of week | 0-7 (0 and 7 are Sunday) |
Special signs:
*means every value.,is a list, like1,15.-is a range, like1-5./is a step, like*/10for every 10 units.
Shortcuts: @reboot, @hourly, @daily, @weekly, @monthly.
Examples
Run a daily backup at 3:00
0 3 * * * /backup/daily_backup.sh
Clean a folder weekly, Sunday at 1:00
0 1 * * 0 find /tmp -type f -mtime +7 -delete
(It removes files older than 7 days. Avoid rm -rf /tmp/*, which can break running programs.)
Restart a service every night at 2:30
30 2 * * * systemctl restart apache2
(This line needs root. Put it in root's crontab.)
Run every 15 minutes
*/15 * * * * /path/to/script.sh
Run at boot
@reboot /path/to/startup.sh
Best practices
- Test the script manually before you schedule it.
- Use full paths for commands and files, because cron has a short
PATH. - Send the output to a log file:
0 3 * * * /backup/daily_backup.sh >> /var/log/backup.log 2>&1. - Make scripts executable:
chmod +x script.sh. - Add comments with
#above each job. - Set
MAILTO=you@example.comat the top to get the output by email.
Check that cron runs
systemctl status cron
(On CentOS and Red Hat the service is crond.) Look at the logs with grep CRON /var/log/syslog on Ubuntu.
Quick recap
crontab -eto edit, five time fields, then the command.- Use full paths and log the output.