If crontab doesn’t work – autostart a program as a service on your Raspberry Pi


If crontab doesn't work - autostart a program as a service on your Raspberry Pi 1

The usual way to autostart a program on your Raspberry Pi is to use cron. However, I have seen many users get frustrated with a particular app that just wouldn’t start at boot despite being specified in crontab.

It gets even worse because it may work on one setup but not on another – resulting in hours of trial and error.

There is one solution which I have found to work reliably and that is systemd. In this short article, I will show you one example of how I use systemd to launch an MQTT monitoring program.

Introducing systemd

systemd was released with Raspbian Jessie in 2018. I don’t want to bore you with the technical details, but it was a powerful enhancement with functionalities like automatically restarting a program that had crashed.

The setup is only slightly more complicated than adding a line in crontab but it’s worth the effort.

Let’s look at one example.

Autostarting CloudMQTT

For my digital picture frame, I have added an MQTT monitoring program that always runs in the background to check if any new MQTT messages have been received and subsequently acts on them. In this case, the program turns the frame display on or off.

The executable python script is in the file monitor_cloudmqtt.py located in /home/pi.

To create a new service, we first specify a configuration file that tells systemd what to do.

sudo nano /lib/systemd/system/cloudmqtt.service

An empty editor window will come up and I paste this text into the window:

[Unit]
Description=Cloudmqtt Service
After=multi-user.target
 
[Service]
Type=idle
 
User=pi
ExecStart=/usr/bin/python3 /home/pi/monitor_cloudmqtt.py
 
Restart=always
RestartSec=60
 
[Install]
WantedBy=multi-user.target

Just specify the sections “Description” and “ExecStart” according to your needs.

You can set “RestartSec” to “0” if you like. I just want to give the system a minute to avoid any hick-ups.

Save the file and change the permissions to make it readable by all.

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

As the last step, you need to tell the system that you have added this file and want to start the service every time your Raspberry Pi boots up.

sudo systemctl daemon-reload
sudo systemctl enable cloudmqtt.service

Reboot your Pi and you are all set!

Conclusion

You may have stumbled upon this article after having searched for hours for a solution to your autostart problem. I hope systemd will work for you as reliably as it has for many Raspberry Pi users!

Wolfgang Männel

Photography has always been a passion of mine. Since 2005, I have looked at countless ideas on how to enjoy beautiful images digitally, making the experience entertaining, amusing, and stimulating. In my other life, I am an entrepreneur, consultant, and bicyclist based near Frankfurt am Main, Germany.

Recent Content