在 Ubuntu(以及其它使用 systemd 的现代 Linux 发行版)里,“定时器”通常指 systemd timer(配合 .timer 和 .service 单元)。下面按常见排错流程给你一份实用指南。
systemctl list-timers
systemctl list-timers --all
查看你的定时器是否在列表中,以及:
NEXT:下次执行时间LAST:上次执行时间UNIT:对应的 service如果没看到,说明:
daemon-reloadenablesystemctl status your-task.timer
重点看:
Loaded:是否 loadedActive:是否 active (waiting)如果没启用:
sudo systemctl enable --now your-task.timer
定时器文件应放在:
/etc/systemd/system/~/.config/systemd/user/示例:
/etc/systemd/system/backup.timer
/etc/systemd/system/backup.service
修改后必须执行:
sudo systemctl daemon-reload
示例 .timer:
[Unit]
Description=Backup Timer
[Timer]
OnCalendar=*-*-* 02:00:00
Persistent=true
Unit=backup.service
[Install]
WantedBy=timers.target
常见错误:
OnCalendar 格式错误WantedBy=timers.targetUnit= 写错 service 名可校验时间格式:
systemd-analyze calendar "*-*-* 02:00:00"
systemctl status backup.service
journalctl -u backup.service
常见 service 错误:
[Service]
Type=oneshot
ExecStart=/usr/bin/bash /opt/backup.sh
注意:
Type=oneshot 常用于脚本ExecStart 必须是绝对路径journalctl -u your-task.timer
journalctl -u your-task.service
journalctl -f
sudo systemctl start your-task.service
如果 service 手动能跑,但 timer 不跑:
OnCalendar如果是用户定时器:
systemctl --user list-timers
systemctl --user enable --now task.timer
需要:
loginctl enable-linger username
| 问题 | 原因 |
|---|---|
| timer 不触发 | 没 enable |
| 时间不对 | 系统时间错误 |
| service 不执行 | 脚本路径/权限错 |
| 只执行一次 | 忘了 Persistent=true |
| 用户 timer 不跑 | 没开 linger |
如果你愿意,可以把:
.timer 文件.service 文件systemctl status 输出贴出来,我可以帮你精确看是哪一步出错。