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.
python3 /home/pi/my_script.py
sudo nano /etc/systemd/system/myscript.service
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
sudo systemctl start myscript && sudo systemctl enable myscript
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