Linux – How to tell systemd to stop service when it no longer required/wanted

gameslinuxsystemd

I have 10 TF2 game dedicated servers. They are started manually one by one with individual service files

tf2-server-1.service
...
tf2-server-10.service

And they want service hlstatsx

Wants=hlstatsx.service

so it starts when at least one game server starts.

How can I tell systemd to stop the hlstatsx service when none of game servers are running?

I tried option in hlstatsx.service

PartOf=tf2-server-1.service tf2-server-2.service tf2-server-3.service tf2-server-4.service tf2-server-5.service tf2-server-6.service tf2-server-7.service tf2-server-8.service tf2-server-9.service tf2-server-10.service

but it's stopping hlstatsx.service when one of game servers turned off, but others still running. It is not what I need.

Best Answer

You can use the directive StopWhenUnneeded=yes in the dependency target unit file (i. e. hlstatsx.service).