大网数据广告活动
服务器运维问答

How to restart a systemd service when a file has not been modified for a period of time?

· 52CE 我爱测

My setup has a systemd service that should periodically write to a file. I would like to monitor the file for changes, so when it hasn't been modified for a while, I know the service has bugged out. I would like to be able to aut…

问题原文

原帖链接 · pinealan · CC BY-SA 3.0

My setup has a systemd service that should periodically write to a file. I would like to monitor the file for changes, so when it hasn't been modified for a while, I know the service has bugged out. I would like to be able to automatically restart the service when that happens.

I have tried using the path unit file, but it can only start a command when the monitored file is changed, not the other way round.

The opposite question has been asked, where the service needs to be restarted when a file was changed, but the solution doesn't seem to be directly applicable to my situation.

已采纳解答

原帖链接 · Adam V · CC BY-SA 3.0

While the comment answer does bring up a good point on where one should be focusing their energy when dealing with an issue like this (debug and try to determine why it might be hanging?), a possible solution to your question could be to set up a systemd-timer that fires at whatever interval you're looking to check that file, and have that run a script that does your testing and actions. Maybe something like (if you're using 1hr as your interval):

Timer

[~]# cat /etc/systemd/system/checkhung.timer 
[Unit]
Description=Check if file not modified in a while and restart service

[Timer]
OnActiveSec=60min
OnUnitActiveSec=60min

Service

[~]# cat /etc/systemd/system/checkhung.service 
[Unit]
Description=Check if file not modified in a while and restart service

[Service]
Type=oneshot
ExecStart=/usr/local/bin/checker.sh

Script

[~]# cat /usr/local/bin/checker.sh
#!/bin/bash

if [[ $(find /path/to/the/file.txt -mmin +60) ]]
then
    /usr/bin/systemctl restart my-service.service
fi

Note that I haven't tested this, so some tweaking may be necessary.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2018-01-21)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。