在 Debian(以及大多数使用 systemd 的现代 Linux 发行版)里,“定时器”通常指 systemd timer。要让定时器持久化(重启后依然生效、开机自动运行),核心就是:把 unit 文件放对位置 + 启用(enable)。
下面按常见场景说明。
例如:/etc/systemd/system/mytask.service
[Unit]
Description=My Task
[Service]
Type=oneshot
ExecStart=/usr/local/bin/mytask.sh
/etc/systemd/system/mytask.timer
[Unit]
Description=Run My Task
[Timer]
OnCalendar=*-*-* 02:00:00
Persistent=true
[Install]
WantedBy=timers.target
✅
Persistent=true很关键
如果系统关机时错过了触发时间,开机后会补执行一次
sudo systemctl daemon-reload
sudo systemctl enable mytask.timer
sudo systemctl start mytask.timer
✅ enable 会创建开机自启软链接
✅ 重启后定时器依然存在
systemctl list-timers
systemctl status mytask.timer
如果你用的是 用户 systemd(不推荐服务器核心任务):
~/.config/systemd/user/mytask.timer
启用:
systemctl --user enable mytask.timer
⚠ 注意:
loginctl enable-linger <user> 才能保证关机后还能跑如果你说的是 cron:
crontab -e
0 2 * * * /usr/local/bin/mytask.sh
✅ cron 本身是持久化的
✅ 重启后自动生效
❌ 不支持“错过时间补跑”
❌ 只 start 不 enable → 重启失效
❌ 文件放错目录(必须 /etc/systemd/system/)
❌ 忘记 daemon-reload
❌ 用 cron @reboot 但脚本路径不对
Debian 定时器持久化 = systemd timer + enable + Persistent=true
如果你愿意,可以告诉我:
我可以直接帮你写一份完整配置。