I have a PHP script that runs indefinitely, performing a specific task every 5-10 seconds (a do-while loop, checks the database at the end of every iteration to determine whether or not it should continue). This task includes MySQL database queries. What is the best way to handle the database connection? Should I:
a.) disconnect and then reconnect to the database every iteration?
b.) set the connection timeout to an indefinite limit?
c.) ping the database to make sure I’m still connected, and reconnect if necessary before executing and queries?
d.) Something else?
EDIT: To clarify, the script sends a push notification to users’ iPhones.
The suggestion that you cannot run your PHP script as a daemon is ridiculous. I’ve done it several times, and it works quite well. There is some example code to get you started. (Requires PEAR… if you’re not a fan, roll your own.)
Now, on to your actual question. If you are making regular queries, your MySQL connection will not timeout on you. That timeout is for idle connections. Definitely stay connected… there is no reason for the overhead of disconnecting and reconnecting. In any case, on a database failure, since your script is running as a daemon, you probably don’t want to immediately kill the process.
I recommend handling the exception and reconnecting. If your reconnect fails, fall back for a little while longer before trying again. After a handful of failures (whatever is appropriate), you may kill the process at that time, as something is probably broken that requires human intervention.