I am running a Paho MQTT client on my raspberry pi (Stretch OS). This script recieves MQTT messages from a publisher script and then stores the data in a SQL database. As I added client.loop_forever() at the end of the script, it can continuously listen for published messages. I can confirm that the script works when I run it manually on terminal as the SQL database becomes updated with new data (as well as printing output in terminal). When I try to configure it for auto start however, it does not seem to work.
I have tried several ways to autostart the script on boot up. I have first used crontab. In crontab, the line I entered reads like this: @reboot python /home/user/project/MQTTclientscript.py I tried restarting the device a few times, but it does not work (i.e. does not send the data into my SQL database which otherwise works when I run manually on terminal). The other programs that are also run via crontab works e.g. 10 * * * * python /home/user/project/demoproject.py
I then tried to rephrase the line in crontab like this: @reboot /usr/bin/python /home/user/project/MQTTclientscript.py, but it still does not work after I reboot. The other programs in crontab still works via this method.
I then tried to edit another file as an alternative approach by typing sudo nano /etc/rc.local in terminal. I then added python /home/user/project/demoproject.py above the line exit 0. This approach however did not work when I rebooted the device.
Running out of options, I then tried to access crontab via sudo crontab -e. I listed my startup programs into the file and rebooted the device. Again, the MQTT client program did not work (i.e. update SQL database).
To troubleshoot, I entered @reboot python /home/user/project/MQTTclientscript.py> output_file.txt in crontab. There is a blank output file produced which I think shows that the script is running.
My question is if it is running, why is it not working in the background as I want it to be, upon boot up? When I run the script from bash commands in terminal, it works well however. Any thought on this?