How to loop PHP script forever on VPS?

I have a PHP script that loops forever, I would like to run it in the background on my VPS and I’m not sure how.

  • I have full root access to my VPS, it’s running CentOS 5.3
  • I don’t use CRON because it needs to run more frequently than once a minute, about every 5 seconds
  • I don’t trigger the script after a web visitor’s action, as it might take a long time to run, which would make the user wait and might trip over the max execution time
  • The script has a loop built into it (as opposed to calling it frequently from elsewhere) because each iteration (which might be slow) needs to be finished before the next iteration starts
  • I can call the script directly from the terminal, and it runs in a loop as desired, but I lose it once I close the terminal session
  • My Linux skills are mediocre

Any ideas? Thanks.

Use “nohup” if you want your script to keep running after you disconnect.

The best solution, however, would be to write a shell script that would be executed from crontab once in a few minutes to check whether your php script is still alive and would re-run it if it is not.

Alternately, run it within a screen. This will keep running after you disconnect and you can reattach to the screen to see any output.