shaunoneil.dev

User Services with Systemd

2023-05-08

This could be useful, but isn't something I've seen used much.

Preparing the account

enable-linger in loginctl if we want processes to outlive the user session. Optional: Create a user for the app.

sudo useradd -m testapp
sudo loginctl enable-linger testapp

If using sudo to access the account, systemctl will complain because we've inherited XDG_RUNTIME_DIR from the environment, so we replace that with the running user:

export XDG_RUNTIME_DIR=/run/user/$(id -u)

Starting a service with a unit

mkdir -p ~/.config/systemd/user/
vim ~/.config/systemd/user/testapp.service

And insert contents:

[Unit]
Description=Test Application
After=network.target

[Install]
WantedBy=default.target

[Service]
WorkingDirectory=%h/approot
ExecStart=%h/approot/app.py

Now we can:

systemctl --user daemon-reload
systemctl --user status testapp.service

systemctl --user start testapp.service
systemctl --user enable testapp.service

..etc.

Starting a one-shot process with a unit

As before, but:

[Service]
Type=oneshot
WorkingDirectory=%h/approot
ExecStart=%h/approot/app.py

Starting a service with a timer

This uses the oneshot service above, but with a timer unit to start it periodically Create a file ~/.config/systemd/user/testapp.timer

[Unit]
Description=Run testapp every 30 minutes

[Install]
WantedBy=timers.target

[Timer]
OnBootSec=3min
OnUnitActiveSec=30min

And start with:

systemctl --user enable --now testapp.timer