How can I configure a systemd service to restart p

2019-03-08 14:29发布

I have a simple systemd service that needs to be periodically restarted to keep its process from bugging out. Is there a configuration option for systemd services to periodically restart them? All of the Restart* options seem to pertain to restarting the service when it exits.

5条回答
迷人小祖宗
2楼-- · 2019-03-08 15:02

How about a crontab like

30 3 * * sun /bin/systemctl restart yourService

which would restart the service yourService at 3:30am each Sunday.

查看更多
霸刀☆藐视天下
3楼-- · 2019-03-08 15:10

I saw a solution here that seemed elegant, if a bit roundabout. The key idea is to create a one-shot service triggered by a timer that restarts another service.

For the timer:

[Unit]
Description=Do something daily

[Timer]
OnCalendar=daily
Persistent=true

[Install]
WantedBy=timers.target

For the one-shot service:

[Unit]
Description=Restart service

[Service]
Type=oneshot
ExecStart=/usr/bin/systemctl try-restart my_program.service

For the one-shot service on Ubuntu 16.04 LTS:

[Unit]
Description=Restart service

[Service]
Type=oneshot
ExecStart=/bin/systemctl try-restart my_program.service

This solution lets you leverage systemd's timers, including the ability to restart the service at a particular time of day, and not just after some amount of time has elapsed.

查看更多
forever°为你锁心
4楼-- · 2019-03-08 15:14

This may not have been present at the time the question was asked, but there is now an option called RuntimeMaxSec, which terminates the service after it has been running for the given period of time.

e.g.

[Service]
Restart=always
RuntimeMaxSec=604800

To me this seems more elegant than abusing Type=notify and WatchdogSec.

查看更多
三岁会撩人
5楼-- · 2019-03-08 15:15

Just some alternate approaches to ultimately reach the same goal:

  • if you have control over the service implementation you could make it end voluntarily after a while, for example either plain exiting after a certain number of iterations (if applicable) or using a timeout timer with a handler sendin itself a SIGTERM/SIGKILL
  • if voluntary service ending is not feasible/practical you could have a small cron-based script killing the service process(es).
查看更多
兄弟一词,经得起流年.
6楼-- · 2019-03-08 15:26

Yes, you can make your service to restart it periodically by making your service of Type=notify. Add this option in [Service] section of your service file along with Restart=always and give WatchdogSec=xx, where xx is the time period in second you want to restart your service. Here your process will be killed by systemd after xx time period and will be restarted by systemd again. for eg.

[Unit]
.
.

[Service]
Type=notify
.
.
WatchdogSec=10
Restart=always
.
.

[Install]
WantedBy= ....
查看更多
登录 后发表回答