The objective of this tutorial is to create a system service in order to run a standalone program on background.

Prerequisites

Create Service

a. Create new service

sudo vim /lib/systemd/system/myservice.service

b. Edit parameters

[Unit]
Description=MyService
After=multi-user.target

[Service]
Type=simple
ExecStart=/usr/bin/python /opt/script.py
Restart=on-abort
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target

c. Enable execution permission of your service

sudo chmod 644 /lib/systemd/system/myservice.service

d. Enable execution permission of your script

sudo chmod u+x /opt/script.py 

e. Create symbolic link

sudo ln -s /opt/script.py /usr/bin/myservice

f. Reload daemon

sudo systemctl daemon-reload

g. Enable the service

sudo systemctl enable myservice.service

h. Start the service

sudo systemctl start myservice.service

i. Check status

sudo systemctl status myservice.service

Useful commands

  • Stop the service
    sudo systemctl stop myservice.service
    

See more here