Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep a persistent PHP script running?

I have a PHP script that listens for incoming socket requests, etc. I need this script to be continually running (it runs within an infinite loop) on the server.

How can I initiate and manage this process? I tried just starting it up through SSH/putty but as soon as the SSH connection times out the script dies.

like image 850
Andy Hin Avatar asked Jan 17 '11 19:01

Andy Hin


People also ask

How do I make PHP scripts run forever?

For allowing to run the script forever and ignore user aborts, set PHP inbuilt function ignore_user_abort(true). By default, it set to False which throws fatal error when client aborts to stop the script.

Can a PHP script run forever?

Whenever a PHP application rebuilds MySQL indexes, the process may run for a long time. Generally, allowing a PHP script to run forever is not desirable.


2 Answers

If long-running reliability is the goal then, supervisord is perfect for this!

I came across it via https://lornajane.net/posts/2012/watch-over-long-running-processes-with-supervisord

Edit: This tool's purpose is to solve the stated problem. The stated goal is to keep the long-running process running. A comment pointed out (validly) that the currently accepted solution will not be reliable, as the script will likely crash etc. So the solution is to use a tool to "initiate and manage this process", that also keeps it alive. This tool does exactly that: it starts the process in the background and keeps it running.

like image 154
legoblocks Avatar answered Sep 20 '22 18:09

legoblocks


We recently had a similar need. We are running an Ubuntu 14.04 LTS server, so created an upstart process to start the process at boot as and restarts if it exits for any reason.

It's worked out extremely well for us, including the automatic restart; our long-running process eventually looses the MySQL connection. The script handles the exception and exits, before the upstart process automatically restarts the process. We have also added a cron script to monitor the process, just in case there is a bigger error that upstart gives up trying to restart; we have a fail-safe in the event a simple restart doesn't correct the prior error.

like image 30
KDrewiske Avatar answered Sep 24 '22 18:09

KDrewiske