简体   繁体   中英

Running a python script automatically after mysql starts on raspberry pi boot

I have written a python script that communicates with a mysql database. I made it start automaticalliy on boot by creating a launcher.sh file:

#!/bin/sh
#launcher.sh
cd /
cd home/pi/
sudo python ser.py
cd /

and adding

@reboot sh /home/pi/launcher.sh >/home/pi/logs/cronlog 2>&1

to the last line of the crontab by:

sudo crontab -e

when system reboots script tries to start working but it cannot connect to the mysql databse. When I start script by connecting with ssh everything works fine.

How can I start my script on boot automatically after all database services starts?

I ran into a similar problem recently.

A poor man's solution - sleep

By using sleep command you give MySQL server time to start (in most of Raspberry Pi use cases 5 seconds should be more than enough). It is not the most elegant solution but unless you are doing something that may affect MySQL server start time by a huge margin, this should do:

#!/bin/sh
#launcher.sh
sleep 5
cd /
cd home/pi/
sudo python ser.py
cd /

A more advanced solution - script that checks if MySQL server has started

The basic idea is to attempt to connect to a local mysql server inside a loop and execute a query, exit, then evaluate the exit code. If the exit code is positive, run your part of the script, else retry.

mysql -e "desc mysql.user" -u <user> -p<password> >/dev/null

You can find a very nice script that does such a thing here: http://forum.osmc.tv/showthread.php?tid=14823

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM