温馨提示×

ubuntu定时器如何排错

小樊
49
2026-10-06 23:58:54
栏目: 智能运维

在 Ubuntu(以及其它使用 systemd 的现代 Linux 发行版)里,“定时器”通常指 systemd timer(配合 .timer 和 .service 单元)。下面按常见排错流程给你一份实用指南。


一、确认定时器是否存在并启用

systemctl list-timers
systemctl list-timers --all

查看你的定时器是否在列表中,以及:

  • NEXT:下次执行时间
  • LAST:上次执行时间
  • UNIT:对应的 service

如果没看到,说明:

  • 文件没放对位置
  • 没执行 daemon-reload
  • 没 enable

二、检查定时器状态

systemctl status your-task.timer

重点看:

  • Loaded:是否 loaded
  • Active:是否 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.target
  • Unit= 写错 service 名

可校验时间格式:

systemd-analyze calendar "*-*-* 02:00:00"

五、检查对应的 service 是否执行成功

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
  • 检查系统时间是否正确
  • 检查是否处于 suspend / 关机状态

八、用户级定时器特别注意事项

如果是用户定时器:

systemctl --user list-timers
systemctl --user enable --now task.timer

需要:

  • 用户已登录
  • 或启用 linger:
loginctl enable-linger username

九、常见坑总结

问题 原因
timer 不触发 没 enable
时间不对 系统时间错误
service 不执行 脚本路径/权限错
只执行一次 忘了 Persistent=true
用户 timer 不跑 没开 linger

如果你愿意,可以把:

  • .timer 文件
  • .service 文件
  • systemctl status 输出

贴出来,我可以帮你精确看是哪一步出错。

0 踩