To create a background service, a systemd service file is needed. It can be create in ~/.config/systemd/user/ with the extension .service for user-level services, or in /etc/systemd/system/ with the extension .service for system-level ones.
The content of the service file should include the [Unit], [Service], and [Install] sections. For example:
[Unit]
Description=My Background Service
[Service]
ExecStart=/path/to/your/executable
Restart=always/on-failure/...
[Install]
WantedBy=default.target/multi-user.target/...
The key fields to note are ExecStart, Restart, and WantedBy.
ExecStartspecifies the command to run the service.Restartspecifies when you want the service to restart: always (after quit), when quited unexpectedly, etc.WantedByspecifies the target to depend on. The perhaps most common one,default.target, means the service will start when user logs in.
Here is my Syncthing service file:
[Unit]
Description=Syncthing
After=network.target
[Service]
ExecStart=/opt/syncthing/syncthing serve --no-browser
Restart=on-failure
RestartSec=5
[Install]
WantedBy=default.target
Interpretation: The file defines a service that is called Syncthing. It auto starts when user logs in by calling syncthing serve --no-browser (the command to start the Syncthing server), after the network is up. It restarts everytime it crashes after waiting for 5 seconds.