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

fault-tolerancemonitoringsystemd

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.

Best Answer

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.