用途
cron 是 Unix 系统标准的任务调度器。通过 cron 表达式(分、时、日、月、星期)定义计划,让脚本自动运行。它适用于备份、日志轮转、数据同步、健康检查以及任何需要周期性执行的任务。
主要能力
- 使用 cron 表达式定义调度时间,格式为:minute hour day month weekday command。
- 字段取值范围:分钟 0-59,小时 0-23,日期 1-31,月份 1-12,星期 0-7(0 表示周日)。
- 支持常见调度模式,例如每天、每小时、每 15 分钟、工作日、每月第一天、每周日等。
- 支持系统级 cron 文件(如 /etc/cron.d/),可指定以特定用户身份运行任务。
使用方式
第一步:Crontab 基础
编辑 crontab:
crontab -e
格式:minute hour day month weekday command
┌─── minute (0-59)
│ ┌─── hour (0-23)
│ │ ┌─── day of month (1-31)
│ │ │ ┌─── month (1-12)
│ │ │ │ ┌─── day of week (0-7, 0=Sun)
│ │ │ │ │
* * * * * command
第二步:常见调度示例
# Every day at 3 AM
0 3 * * * /opt/scripts/backup.sh
# Every hour
0 * * * * /opt/scripts/health-check.sh
# Every 15 minutes
*/15 * * * * /opt/scripts/sync-data.sh
# Monday to Friday at 9 AM
0 9 * * 1-5 /opt/scripts/daily-report.sh
# First day of every month at midnight
0 0 1 * * /opt/scripts/monthly-cleanup.sh
# Every Sunday at 2 AM
0 2 * * 0 /opt/scripts/weekly-maintenance.sh
第三步:最佳实践
# Always redirect output to a log file
0 3 * * * /opt/scripts/backup.sh >> /var/log/backup.log 2>&1
# Use full paths (cron has minimal PATH)
0 * * * * /usr/bin/node /opt/app/scripts/job.js
# Set environment variables
MAILTO=admin@example.com
PATH=/usr/local/bin:/usr/bin:/bin
SHELL=/bin/bash
0 3 * * * /opt/scripts/backup.sh
第四步:系统 Cron(root 任务)
# /etc/cron.d/app-maintenance — System-level cron file
SHELL=/bin/bash
PATH=/usr/local/bin:/usr/bin:/bin
# Database backup as postgres user
0 3 * * * postgres pg_dump myapp > /backups/myapp-$(date +\%Y\%m\%d).sql
# Log rotation
0 0 * * * root /usr/sbin/logrotate /etc/logrotate.conf
适用场景
- 按计划运行脚本。
- 设置自动化备份。
- 安排数据处理任务。
- 日志轮转、数据同步、健康检查等周期性任务。
限制与注意事项
- 在 cron 中始终使用完整路径,因为 cron 的 PATH 很有限。
- 将输出重定向到日志文件或 /dev/null,未处理的输出会通过邮件发送。
- 使用 crontab -l 列出任务,crontab -e 编辑,crontab -r 删除全部(需谨慎)。
- 如需带依赖跟踪的现代替代方案,可使用 systemd timers。
- 在将命令放入 cron 之前,先手动测试命令。