Skip to content

Instantly share code, notes, and snippets.

@drmalex07
Last active July 7, 2024 19:47
Show Gist options
  • Save drmalex07/d006f12914b21198ee43 to your computer and use it in GitHub Desktop.
Save drmalex07/d006f12914b21198ee43 to your computer and use it in GitHub Desktop.
An example with an oneshot service on systemd. #systemd #systemd.service #oneshot

README

Services declared as oneshot are expected to take some action and exit immediatelly (thus, they are not really services, no running processes remain). A common pattern for these type of service is to be defined by a setup and a teardown action.

Let's create a example foo service that when started creates a file, and when stopped it deletes it.

Define setup/teardown actions

Create executable file /opt/foo/setup-foo.sh:

#!/bin/bash
echo "Setting up foo ..."
touch /tmp/foo-activated

Create executable file /opt/foo/teardown-foo.sh:

#!/bin/bash
echo "Tearing down foo ..."
if [ -f /tmp/foo-activated ]; then
    rm /tmp/foo-activated
else
    echo "Doesnt seem to be up: Skipping ..."
fi

Define the service unit

Now, we define the systemd unit file as /etc/systemd/system/foo.service. Note that we must specify RemainAfterExit=true so that systemd considers the service as active after the setup action is successfully finished.

[Unit]
Description=Setup foo
#After=network.target

[Service]
Type=oneshot
ExecStart=/opt/foo/setup-foo.sh
RemainAfterExit=true
ExecStop=/opt/foo/teardown-foo.sh
StandardOutput=journal

[Install]
WantedBy=multi-user.target

Reload the systemd daemon and start the service as normally (systemctl start foo.service). Check the status to verify that the correct actions are taking place.

@drmalex07
Copy link
Author

@xundeenergie
The problem with your setup is that systemd will have no idea when your backup is finished.
A solution would be to define a service of Type=simple (with RemainAfterExit=false) and modify your backup program to stay alive (e.g by waiting on a lock file) until all children processes have finished (successfully or not).
These kinds of services are easily activated by timers.

If the program that performs the backup is out of your control, then you should maybe resort in a plain-old cronjob.

@James-E-A
Copy link

This description was very helpful even for configuring my service which did not require an ExecStop; now I know how to actually write these correctly

@shirobachi
Copy link

Thanks for sharing, helpful for begginer like me :)

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