crontab — scheduled job management
💬 "crontab command"
crontab executes tasks at scheduled times. It is a basic tool for backups, cleanup, and batch jobs.
The most common issues are environment variables (PATH) and output redirection.
- Concept: Specifies the execution schedule in the order minute, hour, day, month, weekday.
- Five fields: the time is specified in this order:
*. - Command: write the command to run after the fields.
- Output: it is safe to append > logfile 2>&1.
Commonly used options
| Option | Description |
|---|---|
| -l | View current schedules |
| -e | Edit schedules (uses editor) |
| -r | Delete all schedules (dangerous) |
| MAILTO= | Turns off or sets mail delivery |
3 essential command combinations
crontab -l— view current schedules0 3 * /opt/app/bin/backup.sh > /var/log/app/backup.log 2>&1— backup every day at 03:00/5 * /opt/app/bin/health.sh >/dev/null 2>&1— health check every 5 minutes
💬 "How should I use this when responding to incidents?"
Common situations on production servers are organized below in order.
Step 1 · View schedules
Check for duplicates with existing jobs.
crontab -l
Step 2 · Add the job
Add it so that logs are kept.
crontab -e # 0 3 * * * /opt/app/bin/backup.sh > /var/log/app/backup.log 2>&1
Step 3 · Verify
Check the logs and execution history.
tail -n 20 /var/log/app/backup.log && grep CRON /var/log/syslog | tail -5
How it is used in practice
1. Nightly backup
Situation — You need to back up a DB dump every day in the early morning.
0 3 * * * /usr/local/bin/db-dump.sh > /var/log/app/dump.log 2>&1
Result — The dump runs every day at 03:00 and logs are kept.
Point — Write scripts using absolute paths, and set PATH inside the script.
2. Temporary file cleanup
Situation — You need to periodically empty the cache directory.
30 4 * * * find /var/cache/app -type f -mtime +7 -delete > /dev/null 2>&1
Result — Cache files older than 7 days are cleaned up every day.
Point — For delete operations, narrow the target path and keep logs for verification.
Important notes
- The cron environment differs from a login shell, so PATH and environment variables are empty. Use absolute paths.
- If you do not redirect output, mail can pile up or logs can be lost.
- crontab -r deletes all schedules. Back them up with -l before using it.
- If you do not check the server time zone, jobs may run at unexpected times.
Actual execution screen
This is the result of checking the schedule list and backup execution log.
!crontab command execution result: schedule list and execution log
Production server in actual operation
Source (HTML): https://games.aidebatehub.com/programs/linux/automation/crontab.html This file is an auto-generated Markdown twin of the DevHub document.
AI Knowledge Hub
Visitor Comments