Starting a User Service on Suspend

Systemd user services are a great way to run services as your user for as long as you are logged in or also during the complete uptime of your system. Some people use it for example to manage their mpd. After learning about them, I thought that they would a great way to lock my laptop and mute any music whenever I suspend. Just put a few user services before suspend.target. However, for security reasons user services are not notified of such system targets. My way around this is a system unit user-suspend@.service that forwards any of the interesting targets to my user’s systemd instance.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[Unit]
Description=sleep.target of a systemd user session
Before=suspend.target sleep.target hibernate.target
StopWhenUnneeded=yes

[Service]
Type=oneshot
ExecStart=/usr/bin/systemctl --user start suspend.target
ExecStop=/usr/bin/systemctl --user stop suspend.target
User=%I
Environment=DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/%I/bus
RemainAfterExit=yes

[Install]
WantedBy=suspend.target sleep.target hibernate.target

Then enable it for your user’s id with sudo systemctl enable user-suspend@$(id -u).service and create the following proxy target in ~/.config/systemd/user/suspend.target.

1
2
3
[Unit]
Description=Proxy for the system-wide suspend.target etc.
StopWhenUnneeded=yes

Now you can use suspend.target in your user services the same as in system units.

1
2
3
4
5
6
7
8
9
10
[Unit]
Description=Mute the system
Before=suspend.target

[Service]
Type=oneshot
ExecStart=/usr/bin/pacmd set-sink-mute 0 1

[Install]
WantedBy=suspend.target