Restart Systemd service automatically whenever a directory changes (any file inside it)

How do I restart a Systemd service when a file change. I've got a Java service that I want to reload when any jar file changes.

This is my setup:

srv.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.path

[Path]
PathModified=/opt/srv/lib/

I also tried using PathChanged and using a file instead a directory.

When I installed the service I executed: sudo systemctl daemon-reload and sudo systemctl enable srv

Thanks!


Michal Politowski's comment is exactly correct. I use this method to automatically restart services when new artifacts are deployed. It is very helpful.

To be clear, you need:

srv.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.service

[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

The answer above is almost great, but it's missing a few things that took me a while to figure out. Others came across the same issues, see the comments section.

systemctl enable srv-watcher.{path,service}
systemctl start srv-watcher.{path,service}

srv.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.service

[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

If it is working, you will see these messages in journalctl

$: journalctl -f -o cat -u srv-watcher
Starting srv-watcher...                                                                                          
Started srv-watcher.

Other things to note, patch may fire many times but the srv-watcher.service will respect the default limit of 5 restarts in 10 second intervals. https://www.freedesktop.org/software/systemd/man/systemd.unit.html#StartLimitIntervalSec=interval