bash – Cannot execute a mqtt server after booting a Raspberry with crontab -e / @reboot

I have programmed in Python several mqtt driven servers on a Raspberry Pi W (with Buster) to execute a set of commands when receiving a given mqtt message from the mqtt broker after subscribing to a set of topics (turn on/off gpios, read and publish through mqtt temperatures, etc…).

This Raspberry is to be installed on a remote location and I want to execute these programs after booting so as to guarantee that they will be active even if a temporary loss of electrical supply happens and the Raspi reboots after the blackout.

I have included a @reboot entry in “sudo crontab -e” to launch a bash file starting the several servers after booting:

@reboot /usr/bin/sleep 60 && /home/pi/p/mqtt/mqtt201.sh

The sleep 60 is to give time the Raspberry to finish the booting process before starting the programs.

The bash file to execute is quite simple:

#!/bin/bash
/usr/bin/python3 /home/pi/p/mqtt/alive201.py >> /home/pi/p/mqtt/alive201.log 2>&1 &
/usr/bin/python3 /home/pi/p/mqtt/led201-05.py >> /home/pi/p/mqtt/led201-05.log 2>&1 &
/usr/bin/python3 /home/pi/p/mqtt/led201-27.py >> /home/pi/p/mqtt/led201-27.log 2>&1 &
/usr/bin/python3 /home/pi/p/mqtt/temp201b_mqtt.py >> /home/pi/p/mqtt/temp201b_mqtt.log 2>&1 &

After booting, when I ssh to the Raspi none of the servers are running because all of them have exited after an error signaled as follows:

Traceback (most recent call last):
  File "/home/pi/p/mqtt/alive201.py", line 1, in <module>
    import paho.mqtt.client as mqtt
ModuleNotFoundError: No module named 'paho'
Traceback (most recent call last):
  File "/home/pi/p/mqtt/alive201.py", line 1, in <module>
    import paho.mqtt.client as mqtt
ModuleNotFoundError: No module named 'paho'

In other words, for some reason, when the programs are executed, paho-mqtt module is not loaded and is not available for the programs to execute.

If after booting I ssh to the Raspberry and I run the bash file manually, the servers are started and everything goes fine.

Does anybody know how can I start my servers through crontab @reboot option with the bash script without facing the problem of the non-availability of paho-mqtt module ?

Thanks and best regards

Read more here: Source link