Skip to content

Instantly share code, notes, and snippets.

@oprypin
Last active November 10, 2024 20:56
Show Gist options
  • Save oprypin/0f0c3479ab53e00988b52919e5d7c144 to your computer and use it in GitHub Desktop.
Save oprypin/0f0c3479ab53e00988b52919e5d7c144 to your computer and use it in GitHub Desktop.
systemd user unit + timer example

Save these files as ~/.config/systemd/user/some-service-name.*

Run this now and after any modifications: systemctl --user daemon-reload

Try out the service (oneshot): systemctl --user start some-service-name

Check logs if something is wrong: journalctl -u --user-unit some-service-name

Start the timer after this user logs in: systemctl --user enable --now some-service-name.timer

[Unit]
Description=Do some thing
After=network.target
[Service]
Type=oneshot
ExecStart=/home/my-user-name/my-service/script.py --some-arg=some-value
[Install]
WantedBy=default.target
[Unit]
Description=Run "Do some thing" every 30 minutes
[Timer]
OnBootSec=3min
OnUnitActiveSec=30min
[Install]
WantedBy=timers.target
@Roy-Orbison
Copy link

You can prefix the executable path with the home directory variable, and your logs may fill with errors if you don't set a working directory, e.g.:

WorkingDirectory=%h
ExecStart=%h/my-service/script.py --some-arg=some-value

OnUnitInactiveSec= may be more suitable for some tasks, it means "time since service last finished".

@manuels
Copy link

manuels commented Sep 19, 2022

https://wiki.archlinux.org/title/systemd/User#Automatic_start-up_of_systemd_user_instances:

The systemd user instance is started after the first login of a user and killed after the last session of the user is closed. Sometimes it may be useful to start it right after boot, and keep the systemd user instance running after the last session closes, for instance to have some user process running without any open session. Lingering is used to that effect. Use the following command to enable lingering for specific user:

loginctl enable-linger $username

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment