The 100 best digital picture frames on amazon
The 100 best digital picture frames on amazon
The 100 best digital picture frames on amazon
The 100 best digital picture frames on amazon

If crontab doesn't work - autostart a pro­gram as a ser­vice on your Rasp­berry Pi

-

The usu­al way to autostart a pro­gram on your Rasp­berry Pi is to use cron. How­ev­er, I have seen many users get frus­trat­ed with a par­tic­u­lar app that just wouldn't start at boot despite being spec­i­fied in crontab.

It gets even worse because it may work on one set­up but not on anoth­er - result­ing in hours of tri­al and error.

There is one solu­tion which I have found to work reli­ably and that is sys­temd. In this short arti­cle, I will show you one exam­ple of how I use sys­temd to launch an MQTT mon­i­tor­ing pro­gram.

Intro­duc­ing sys­temd

sys­temd was released with Rasp­bian Jessie in 2018. I don't want to bore you with the tech­ni­cal details, but it was a pow­er­ful enhance­ment with func­tion­al­i­ties like auto­mat­i­cal­ly restart­ing a pro­gram that had crashed.

The set­up is only slight­ly more com­pli­cat­ed than adding a line in crontab but it's worth the effort.

Let's look at one exam­ple.

Autostart­ing Cloud­MQTT

For my dig­i­tal pic­ture frame, I have added an MQTT mon­i­tor­ing pro­gram that always runs in the back­ground to check if any new MQTT mes­sages have been received and sub­se­quent­ly acts on them. In this case, the pro­gram turns the frame dis­play on or off.

The exe­cutable python script is in the file monitor_cloudmqtt.py locat­ed in /home/pi.

To cre­ate a new ser­vice, we first spec­i­fy a con­fig­u­ra­tion file that tells sys­temd what to do.

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

An emp­ty edi­tor win­dow will come up and I paste this text into the win­dow:

[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 spec­i­fy the sec­tions "Descrip­tion" and "Exec­Start" accord­ing to your needs.

You can set "Restart­Sec" to "0" if you like. I just want to give the sys­tem a minute to avoid any hick-ups.

Save the file and change the per­mis­sions to make it read­able by all.

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

As the last step, you need to tell the sys­tem that you have added this file and want to start the ser­vice every time your Rasp­berry Pi boots up.

sudo systemctl daemon-reload
sudo systemctl enable cloudmqtt.service

Reboot your Pi and you are all set!

Con­clu­sion

You may have stum­bled upon this arti­cle after hav­ing searched for hours for a solu­tion to your autostart prob­lem. I hope sys­temd will work for you as reli­ably as it has for many Rasp­berry Pi users!