1

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?

Tui Popenoe
  • 2,098
  • 2
  • 23
  • 44
Kursat Serolar
  • 147
  • 2
  • 12

1 Answers1

0

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

Paweł Duda
  • 1,713
  • 4
  • 18
  • 36