Raspi backgroud service

nguyennamdsn | March 16, 2023, 6:52 a.m.

1. Introduction

There are several ways to execute a piece of code when your Raspberry Pi boots. You can, for instance, use the nickname @reboot in crontab in order to launch an script after rebooting your machine. You can also configure crontab to run the script every X minutes. However, if you want to create a Raspberry Pi service that runs at boot time, considers dependencies and keeps on running in the background, you should use systemd.

2. Creating a Raspberry Pi service

Systemd is an init system used in Linux distributions to bootstrap the user space and to manage system processes after booting. It includes a collection of tools for a range of different tasks. Its primary purpose is to initialise, manage and track system services and daemons, both during start-up and while the system is running.

Creating a .service file with the following structure: sudo vi /etc/systemd/system/test.service
[Unit]
Description=SERVICE NAME
After=network-online.target

[Service]
ExecStart=/bin/bash SCRIPT_PATH
WorkingDirectory=SCRIPT_HOME_PATH
StandardOutput=inherit
StandardError=inherit
Restart=always
User=USER_NAME

[Install]
WantedBy=multi-user.target

Just adapt the code to the path used in your system. The line After=network-online.target will postpone the start of the service until the network is in up status. If you want to know more about some of the options used, I recommend you to read the following article.

To enable service:

sudo systemctl daemon-reload
sudo systemctl enable test.service  
sudo systemctl start test.service
sudo systemctl status test.service


refer: https://domoticproject.com/creating-raspberry-pi-service/

0
2

Leave a comment:

Comments:

NBzoZGmS Jan. 30, 2024, 11:24 a.m. wrote:

YeDsbZjkNrvPWEgB

NBzoZGmS Jan. 30, 2024, 11:24 a.m. wrote:

YeDsbZjkNrvPWEgB