mobile ecommerce development

Creating A Service on your Raspberry Pi

A service is best used for an application you’d like to run continuously on your pi. Maybe it’s a script that’s constantly checking for weather station data and sending it to the cloud, or a simple app that listens for requests to change a LED strip’s color. If you’re looking for something that can handle restarts automatically, and starts when the Pi starts - a service is a great solution.

1. To create a service, first test if the script you’d like to run is functioning properly. Make sure to use the full path to the file when invoking it.

python3 /home/pi/my_script.py

2. Next, we’ll create a file in /etc/systemd/system to define our service:

sudo nano /etc/systemd/system/myscript.service

3. We’ll then edit the file, adding the required information to define the service and allow it to restart on failure.

sudo nano /etc/systemd/system/myscript.service
Add the following lines to the file

[Unit]
Description=My long running script
After=network.target
StartLimitIntervalSec=0[Service]
Type=simple
User=pi
Restart=always
RestartSec=1
ExecStart=python3 /home/pi/my_script.py

[Install]
WantedBy=multi-user.target

 

4. Once you’ve saved your file, start and enable the service - allowing it to run immediately, and also when the pi restarts.

sudo systemctl start myscript && sudo systemctl enable myscript

5. Your script will now run on your pi in the background, restarting automatically when it fails. You can check on it with the following command:

sudo systemctl status myscript
And that’s it. Many services are already running on your Pi as a part of it’s normal operation. By defining and enabling this service, you simply add your script to the rest of the things your Pi does just by being plugged in. If at any point you need to stop the service, you can do it with the following command:

sudo systemctl stop myscript
There are many other ways to accomplish running scripts in the background, but for Raspberry Pi projects, these two are my go-to commands. Happy building!

# pick any session name you like
tmux new -s your_session_name

Get in touch