systemd 控制服务 service 开机延迟启动

151 阅读2分钟

以下是一个 HelloWorld 服务的示例,它将在 系统启动 60 秒后自动启动,而不是立即启动。

1. helloworld.service(服务文件)

这个文件定义了一个简单的 HelloWorld 服务,它运行一个 helloworld.sh 脚本。

文件路径: /etc/systemd/system/helloworld.service

[Unit]
Description=HelloWorld Service
After=network.target remote-fs.target nss-lookup.target

[Service]
ExecStart=/bin/bash /opt/helloworld/helloworld.sh
Restart=always
RestartSec=5
StandardOutput=journal
StandardError=journal

[Install]
# 不要 WantedBy=multi-user.target,因为它不应该在开机时立即启动

🔹 重点

  • ExecStart=/bin/bash /opt/helloworld/helloworld.sh → 运行 helloworld.sh 脚本。
  • 没有 [Install] WantedBy=multi-user.target,所以 helloworld.service 不会在开机时自动运行
  • helloworld.timer 负责控制它何时启动。

2. helloworld.timer(定时器文件)

这个 timerhelloworld.service 在系统启动 60 秒后自动启动

文件路径: /etc/systemd/system/helloworld.timer

[Unit]
Description=Run HelloWorld Service 60 seconds after boot
After=network.target remote-fs.target nss-lookup.target

[Timer]
OnBootSec=60s
Unit=helloworld.service

[Install]
WantedBy=timers.target

🔹 重点

  • OnBootSec=60s开机 60 秒后 触发 helloworld.service
  • Unit=helloworld.service → 这个定时器触发 helloworld.service
  • WantedBy=timers.target → 让 helloworld.timer 在系统启动时自动运行

3. helloworld.sh(示例脚本)

可以放在 /opt/helloworld/helloworld.sh 并赋予执行权限:

#!/bin/bash
echo "Hello, World! Service started at $(date)" >> /var/log/helloworld.log

赋予执行权限:

sudo chmod +x /opt/helloworld/helloworld.sh

这样,每次 helloworld.service 启动时,都会在 /var/log/helloworld.log 里写入日志。

4. 启用和测试

(1) 让 helloworld.service 不能直接自启

sudo systemctl disable helloworld.service

(2) 让 helloworld.timer 在开机时自动启用

sudo systemctl daemon-reload
sudo systemctl enable helloworld.timer
sudo systemctl start helloworld.timer

(3) 检查定时器是否生效

systemctl list-timers --all | grep helloworld

应该能看到 helloworld.timer 计划在 60 秒后启动 helloworld.service

(4) 立即测试

如果不想等 60 秒,可以手动触发:

sudo systemctl start helloworld.service

然后查看日志:

cat /var/log/helloworld.log

(5) 重新启动系统,观察 60 秒后是否启动

sudo reboot

然后在重启后 60 秒检查:

systemctl status helloworld.service

总结

helloworld.service 负责运行 HelloWorld 任务,但 不会开机自启
helloworld.timer 在开机 60 秒后触发 helloworld.service
helloworld.sh 只是一个示例脚本,可以换成你的服务启动脚本。
启用 timer,而不是 servicesystemctl enable helloworld.timer)。

这样,你的 helloworld.service 只会 等 60 秒后启动,而不是一开机就运行!🚀