Skip to content

⏰ cron 定时任务

crontab 基础

cron 是 Linux 自带的定时任务调度器。你告诉它"什么时候执行什么命令",它就准时帮你跑。

bash
# 编辑当前用户的定时任务
crontab -e

# 查看当前用户的定时任务
crontab -l

# 查看所有用户的定时任务(需要 root)
crontab -l -u www-data

# 删除当前用户的所有定时任务(危险!)
crontab -r

时间格式详解

cron 的时间格式是 5 个字段,从左到右:

bash
# ┌───────────── 分钟 (0-59)
# │ ┌───────────── 小时 (0-23)
# │ │ ┌───────────── 日 (1-31)
# │ │ │ ┌───────────── 月 (1-12)
# │ │ │ │ ┌───────────── 星期几 (0-7, 0和7都是周日)
# │ │ │ │ │
  * * * * *  command

# 常用示例:
30 2 * * *       /opt/backup.sh        # 每天凌晨 2:30
0 */4 * * *      /opt/check.sh          # 每 4 小时整点
0 9 * * 1-5      /opt/report.sh         # 工作日 9:00
*/5 * * * *      /opt/ping.sh           # 每 5 分钟
0 0 1 * *        /opt/monthly.sh        # 每月 1 号 0:00
30 8,12,18 * * * /opt/feed.sh           # 每天 8:30, 12:30, 18:30
0 22 * * 1       /opt/weekly.sh         # 每周一 22:00

⚠️ 注意: ⚠️ 常见坑:cron 的环境变量只有PATH=/usr/bin:/bin,脚本里用到node、docker等要写绝对路径cron 的输出默认发邮件,不设MAILTO会报错。加MAILTO=""禁用脚本要有执行权限:chmod +x /opt/backup.sh

完整的 crontab 模板

bash
# ~/.crontab — 推荐的完整模板
SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
MAILTO=""

# === 数据库备份:每天凌晨 2 点 ===
0 2 * * * /opt/scripts/db-backup.sh >> /var/log/db-backup.log 2>&1

# === 健康检查:每 5 分钟 ===
*/5 * * * * /opt/scripts/health-check.sh 2>/dev/null

# === 日志清理:每周日 3 点 ===
0 3 * * 0 find /var/log/app -name "*.log" -mtime +30 -delete

# === 证书续期检查:每天 10 点 ===
0 10 * * * /opt/scripts/cert-renew.sh >> /var/log/cert-renew.log 2>&1

cron vs systemd timer

systemd 也提供了定时任务功能(.timer),比 cron 更强大:

bash
# 创建一个 systemd timer(替代 cron)
cat > /etc/systemd/system/backup.timer << 'EOF'
[Unit]
Description=Daily Backup Timer

[Timer]
OnCalendar=*-*-* 02:30:00
Persistent=true
RandomizedDelaySec=300

[Install]
WantedBy=timers.target
EOF

cat > /etc/systemd/system/backup.service << 'EOF'
[Unit]
Description=Database Backup

[Service]
Type=oneshot
ExecStart=/opt/scripts/db-backup.sh
User=root
EOF

systemctl daemon-reload
systemctl enable --now backup.timer

# 查看 timer 状态
systemctl list-timers --all
特性cronsystemd timer
日志需要自己重定向自动记录到 journalctl
错过执行不补执行Persistent=true会补执行
依赖管理可以等其他服务启动后再执行
资源限制可以限制 CPU/内存
学习成本极低中等
推荐场景简单任务、习惯 cron生产环境、需要日志/补执行