温馨提示×

debian定时器怎么开机启动

小樊
46
2026-10-13 16:33:01
栏目: 智能运维

在 Debian 里“定时器开机启动”通常分两种场景,最常见的是 systemd 定时器(timer),另一种是比较老的 cron @reboot。下面分别说。


一、systemd 定时器(推荐,Debian 8+ 默认)

假设你有一个服务:

/etc/systemd/system/hello.service

[Unit]
Description=Hello

[Service]
ExecStart=/usr/bin/echo hello

和一个定时器:

/etc/systemd/system/hello.timer

[Unit]
Description=Run hello

[Timer]
OnBootSec=1min
OnUnitActiveSec=1h

[Install]
WantedBy=timers.target

开机启动定时器

sudo systemctl enable hello.timer

✅ enable 就是“开机启动”
❌ 只 start 不会开机自启

常用命令

sudo systemctl start hello.timer     # 立即启动
systemctl status hello.timer         # 查看状态
systemctl list-timers                # 查看所有定时器
journalctl -u hello.service          # 看执行日志

二、cron 的 @reboot(简单任务可用)

编辑 crontab:

crontab -e

添加:

@reboot /path/to/script.sh

⚠ 注意:

  • 脚本要有可执行权限
  • 环境变量很少,建议用绝对路径

三、如果是“延时执行一次”的任务

[Timer]
OnBootSec=30s

表示开机 30 秒后执行一次。


四、排查不开机启动的常见原因

  1. 没 enable
  2. 写成了 service 而不是 timer
  3. 系统没用 systemd(极老 Debian)
  4. 脚本路径错误 / 权限不足

如果你愿意,可以把你的 timer 文件或需求贴出来,我可以帮你直接改好。

0 踩