Systemd

User unit

Create unit file ~/.config/systemd/user/test.service :

[Unit]
Description=%u test service
After=multi-user.target
AssertPathExists=%h

[Service]
WorkingDirectory=%h
EnvironmentFile=%h/.local/test.env
UMask=0002
ExecStart=/bin/sh -c 'while true; do echo -e "[ $(date) ] $PROJECT: %n is running on %H"; sleep 15; done'
ExecStop=/bin/kill -TERM $MAINPID
ExecStopPost=/bin/sh -c 'echo -e "[ $(date) ] $PROJECT: %n is stopped on %H"'
Restart=on-failure
Type=simple

[Install]
WantedBy=multi-user.target

Caution

Don’t use User and Group option in service unit file.

Create env file ~/.local/test.env :

PROJECT=Guisam

Enable service unit :

systemctl --user enable test.service

Note

Enabling service create systemd link, LLL [1] :

.config/systemd
└── user
    ├── multi-user.target.wants
    │   └── test.service -> /home/guigui/.config/systemd/user/test.service
    └── test.service

Start, stop service :

systemctl --user start test.service
systemctl --user stop test.service

Check service status :

systemctl --user status test.service
● test.service - guigui test service
   Loaded: loaded (/home/guigui/.config/systemd/user/test.service; enabled; vendor preset: enabled)
   Active: inactive (dead)

nov. 09 17:34:41 laptop.guisam.lan systemd[11727]: Stopping guigui test service...
nov. 09 17:34:41 laptop.guisam.lan sh[29210]: [ Sat 09 Nov 2019 05:34:41 PM CET ] Guisam: test.service is stopped on laptop.guisam.lan
nov. 09 17:34:41 laptop.guisam.lan systemd[11727]: test.service: Succeeded.
nov. 09 17:34:41 laptop.guisam.lan systemd[11727]: Stopped guigui test service.
nov. 09 18:17:10 laptop.guisam.lan systemd[11727]: Started guigui test service.
nov. 09 18:17:10 laptop.guisam.lan sh[635]: [ Sat 09 Nov 2019 06:17:10 PM CET ] Guisam: test.service is running on laptop.guisam.lan
nov. 09 18:17:24 laptop.guisam.lan systemd[11727]: Stopping guigui test service...
nov. 09 18:17:24 laptop.guisam.lan sh[950]: [ Sat 09 Nov 2019 06:17:24 PM CET ] Guisam: test.service is stopped on laptop.guisam.lan
nov. 09 18:17:24 laptop.guisam.lan systemd[11727]: test.service: Succeeded.
nov. 09 18:17:24 laptop.guisam.lan systemd[11727]: Stopped guigui test service.

Display service logs :

journalctl --user -u test.service

Enable persistent session :

sudo loginctl enable-linger <user>

Warning

You need root acces to access enable-linger option. /var/lib/systemd/linger/<user> must exist.

Footnotes

[1]LLL … Lennart like links laugh