分钟 小时 日 月 星期 命令
* * * * * command
# 特殊字符
* 任意值
, 列举 (1,3,5)
- 范围 (1-5)
/ 步进 (*/5 = 每5)
# 每天凌晨 2 点执行备份
0 2 * * * /opt/scripts/backup.sh
# 每 5 分钟检查服务
*/5 * * * * /opt/scripts/healthcheck.sh
# 每周一 9 点发送报告
0 9 * * 1 /opt/scripts/report.sh
crontab -l # 列出当前用户任务
crontab -e # 编辑
crontab -u user -l # 查看指定用户任务
# 系统级配置
cat /etc/crontab
ls /etc/cron.d/ # 系统任务
ls /etc/cron.daily/ # 每天执行的脚本
ls /etc/cron.hourly/ # 每小时
# /etc/systemd/system/backup.service
[Unit]
Description=Backup Service
[Service]
Type=oneshot
ExecStart=/opt/scripts/backup.sh
# /etc/systemd/system/backup.timer
[Unit]
Description=Daily Backup Timer
[Timer]
OnCalendar=daily # 或 Mon *-*-* 02:00:00
Persistent=true # 错过时间点后立即补跑
RandomizedDelaySec=300 # 随机延迟避免惊群
[Install]
WantedBy=timers.target
systemctl enable backup.timer
systemctl start backup.timer
systemctl list-timers
| 特性 | Cron | systemd Timer |
|---|---|---|
| 日志 | syslog | journalctl |
| 随机延迟 | 需 shell 实现 | 内置 |
| 依赖管理 | 无 | 可以 After/Requires |
| 资源控制 | 无 | Cgroups |
| 错过执行 | 不补 | Persistent 可补 |
| 环境变量 | 继承 cron 环境 | 独立配置 |
flock -n /tmp/backup.lock ...timeout 3600 your_script# 带锁和超时的 cron 条目
*/10 * * * * flock -n /tmp/task.lock timeout 300 /opt/scripts/task.sh