在 Debian(以及大多数使用 systemd 的现代 Debian 系统)中,“定时器”通常指 systemd timer(.timer 单元)。下面从常见错误场景 → 排查步骤 → 常用命令 → 示例系统地说一下如何排错。
Debian 常见定时器有两种:
/etc/systemd/system/xxx.timerxxx.service/etc/crontab、/etc/cron.d/*、crontab -e下面以 systemd timer 为主。
systemctl status xxx.timer
重点看:
Loaded:是否加载Active:是否启用Last trigger / Next trigger:是否按预期触发systemctl list-timers
或只看某一个:
systemctl list-timers xxx.timer
常见问题:
enablednext trigger 是 n/a启用定时器:
systemctl enable --now xxx.timer
定时器只是“触发器”,真正干活的是 .service
systemctl status xxx.service
journalctl -u xxx.service
常见问题:
.service 文件写错journalctl -u xxx.timer
journalctl -u xxx.service
实时查看:
journalctl -f -u xxx.service
如果什么日志都没有:
检查点:
systemctl is-enabled xxx.timer
systemctl is-active xxx.timer
解决:
systemctl daemon-reload
systemctl enable --now xxx.timer
错误示例:
OnCalendar= Daily
正确示例:
OnCalendar=*-*-* 03:00:00
验证语法:
systemd-analyze calendar "*-*-* 03:00:00"
.service 示例(易错):
❌ 错误:
[Service]
ExecStart=/root/backup.sh
✅ 正确:
[Service]
Type=oneshot
ExecStart=/bin/bash /root/backup.sh
注意:
Type=oneshotsystemd 环境很“干净”
解决方式:
[Service]
Environment=PATH=/usr/local/bin:/usr/bin:/bin
或在脚本里显式 source
用户 timer:
systemctl --user status xxx.timer
注意:
loginctl enable-linger 用户名NetworkManager 等系统资源/etc/systemd/system/test.timer[Unit]
Description=Test Timer
[Timer]
OnCalendar=*:0/1
Persistent=true
[Install]
WantedBy=timers.target
/etc/systemd/system/test.service[Unit]
Description=Test Service
[Service]
Type=oneshot
ExecStart=/bin/bash -c 'echo $(date) >> /tmp/test.log'
启用:
systemctl daemon-reload
systemctl enable --now test.timer
验证:
cat /tmp/test.log
检查:
systemctl status cron
crontab -l
日志:
grep CRON /var/log/syslog
systemctl daemon-reload
systemctl status xxx.timer
systemctl list-timers xxx.timer
journalctl -u xxx.service
systemd-analyze calendar "你的时间表达式"
如果你愿意,可以把:
.timer 文件.service 文件journalctl 报错贴出来,我可以直接帮你逐行改 ✅