Raspberry Booting Services

Creating a Raspberry Pi service

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.

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.

Monitoring Raspberry temperature with a service

In this example we will create a service that monitors the Raspberry temperature. This service will send an IFTTT notification to the configured smartphone containing the Raspberry’s Pi temperature when this is greater than a certain value. We want to run this script automatically when booting the system, and let it running forever. This is the bash code of our script:

In order to know more about the IFTTT applets, read this post. I have used egrep to extract the temperatures with one decimal and awk to compare floating numbers. logger is used to log the sent alarms, as well as the temperatures recorded, in the system log syslog with the tag tempMonitor. The script will sleep and wake up in the minutes ended in 1 or 6 (01, 06, 11, 16, etc.). To know more about how to calculate this sleep time, see the following post.

Creating a service

To convert the previous script into a service, start creating a .service file with the following structure:

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.

Now copy the file into /lib/systemd/system with root user:

Testing the service

Once this has been copied, you can attempt to start the service using the following command:

Check if it is running correctly by doing:

Stop it using the following command:

And check again if the script is correctly stopped. Once everything is checked, you can configure your service to start automatically on reboot by using the following command:

From now on, you can check easier the status of the service by doing:

Raspberry Pi service CPU Temp IFTTT Notification

3 thoughts on “Creating a Raspberry Pi service

Leave a Comment