解决 systemd 定时器未按期执行与 Unit not found 故障排查
分析 systemd timer 到期未触发任务诱因,详解 OnCalendar 时间表达式校验与同名 service 绑定规范。
问题现象
编写了 .timer 定时器替代 crontab,但到达指定时间后完全没有触发同名 .service 执行,执行 systemctl list-timers 显示状态处于 n/a。
触发根因
- 同名绑定的 .service 单元不存在或拼写错误:默认情况下
mytask.timer会自动触发mytask.service。如果服务名称不一致且未在 timer 中显式指定Unit=,定时器调度落空。 - OnCalendar 时间表达式语法不合法。
解决方案
规范配置与校验时间语法
编辑 /etc/systemd/system/mytask.timer:
[Unit]
Description=Run mytask daily
[Timer]
# 每天凌晨 2 点执行
OnCalendar=*-*-* 02:00:00
# 开启持久化补跑(若关机错过时间点,开机后自动补跑一次)
Persistent=true
# 显式指定绑定的服务名
Unit=mytask.service
[Install]
WantedBy=timers.target
使用 systemd 原生工具校验时间表达式合法性:
systemd-analyze calendar "*-*-* 02:00:00"
启用并启动定时器:
sudo systemctl daemon-reload
sudo systemctl enable --now mytask.timer
验证方法
执行 systemctl list-timers | grep mytask,显示清晰的下次触发倒计时(NEXT),调度机制彻底恢复。


