当文件更改时,如何重新启动 Systemd 服务。我有一个 Java 服务,我想在任何 jar 文件更改时重新加载它。
这是我的设置:
服务提供者
[Unit]
Description=srv 0.1: Service's description
After=network.target
[Service]
Type=simple
WorkingDirectory=/opt/srv
ExecStart=/opt/srv/bin/srv
User=root
Group=root
[Install]
WantedBy=multi-user.target
服务路径
[Path]
PathModified=/opt/srv/lib/
我也尝试使用PathChanged
文件而不是目录。
当我安装服务时我执行了sudo systemctl daemon-reload
: sudo systemctl enable srv
谢谢!
答案1
Michal Politowski 的评论完全正确。我使用此方法在部署新工件时自动重启服务。这非常有帮助。
为了清楚起见,你需要:
服务提供者
[Unit]
Description=srv 0.1: Service's description
After=network.target
[Service]
Type=simple
WorkingDirectory=/opt/srv
ExecStart=/opt/srv/bin/srv
User=root
Group=root
[Install]
WantedBy=multi-user.target
srv-watcher.服务
[Unit]
Description=srv restarter
After=network.target
[Service]
Type=oneshot
ExecStart=/usr/bin/systemctl restart srv.service
[Install]
WantedBy=multi-user.target
srv-watcher.path
[Path]
PathModified=/opt/srv/lib
[Install]
WantedBy=multi-user.target
答案2
上面的答案几乎很棒,但缺少了一些我花了一段时间才弄清楚的东西。其他人也遇到了同样的问题,请参阅评论部分。
systemctl enable srv-watcher.{path,service}
systemctl start srv-watcher.{path,service}
服务提供者
[Unit]
Description=srv 0.1: Service's description
After=network.target
[Service]
Type=simple
WorkingDirectory=/opt/srv
ExecStart=/opt/srv/bin/srv
User=root
Group=root
[Install]
WantedBy=multi-user.target
srv-watcher.服务
[Unit]
Description=srv restarter
After=network.target
StartLimitIntervalSec=10
StartLimitBurst=5
[Service]
Type=oneshot
ExecStart=/usr/bin/systemctl restart srv.service
[Install]
WantedBy=multi-user.target
srv-watcher.path
[Path]
Unit=srv-watcher.service
PathChanged=/opt/srv/lib
# trigger on changes to a file not just create/delete
# don't put comments in the same line as the command
[Install]
WantedBy=multi-user.target
如果它正常工作,您将在 journalctl 中看到这些消息
$: journalctl -f -o cat -u srv-watcher
Starting srv-watcher...
Started srv-watcher.
其他需要注意的是,补丁可能会触发多次,但 srv-watcher.service 将遵守 10 秒间隔内 5 次重启的默认限制。https://www.freedesktop.org/software/systemd/man/systemd.unit.html#StartLimitIntervalSec=interval