What's the best way to keep a PHP script running as a daemon?

If you can't use the (proper) init structure to do this (you're on shared hosting, etc.), use cron to run a script (it can be written in whatever language you like) every few minutes that checks to see if they're running, and restarts them if necessary.


The most elegant solution is reactPHP.


Quick and dirty cron to restart your daemon:

* * * * * USER ps auxww | grep SCRIPTNAME > /dev/null || SCRIPTNAME

Replace USER with the user that the daemon runs as and SCRIPTNAME with the name of your script. Stick this in /etc/cron.d/restart_php_daemon. It should run every minute. Change the first * to */2 or */5 to run less frequently.

UPDATE

If you're putting this into your own crontab:

Run crontab -e and add:

* * * * * ps auxwww | grep SCRIPTNAME > /dev/null || SCRIPTNAME

Tags:

Php

Daemon