Wakenn
Wakenn

Reputation: 391

Constantly run php loop without leaving browser open

I have a php loop that I want to constantly run. Currently if you leave x.php running in your browser then it loops forever. as long as you have the browser window open... and it works great.

How do I get it to run constantly without me having to sit with a browser tab open on it? I want it to run 24/7 and if it ever stops running. it needs to restart itself.

Thanks

Upvotes: 0

Views: 1988

Answers (4)

Rudi Visser
Rudi Visser

Reputation: 21999

It depends how you're triggering PHP.

If you want it to start it's execution in the browser you have several options. You either start a new process in the background (call a shell script using exec, which spawns another php process, for example), or you could try the ignore_user_abort() method provided.

ignore_user_abort(true) will do exactly what it says on the tin, if the user aborts the page request (which will be endlessly running), the backend PHP process will not take notice of this. Note that it doesn't work in all circumstances, for instance you can't send any output back to the browser. Obviously this is because the pipe is closed, but what I mean is that it's not a catchable error, the script will stop executing.

If you're not starting it in the browser, which I would recommend for something like this, I would suggest using a cron with a custom script. I would do it with a cron script that runs every minute. This script would create the PHP Process initially with a PID file, the PHP would process whatever you need it to do. Each subsequent run of the script, it checks that the PID file exists, and if it does, it checks that the process is alive. If not, it will repeat the process/PID file creation as initially planned.

Upvotes: 1

Shawn
Shawn

Reputation: 3369

Not really sure what you are trying to accomplish, however it sounds like what you want to run is a script? If so you want to create a cron tab for it. The syntax can be found here:

http://content.hccfl.edu/pollock/unix/crontab.htm

An example might be:

5/* * * * 1 /usr/bin/php -q /location/to/your/script/file.php

Upvotes: 0

Ignas
Ignas

Reputation: 1965

Read about cron jobs. With their help you can execute any php script to run every minute 24/7.

Upvotes: 0

Ansari
Ansari

Reputation: 8218

Can you run it from the command line?

nohup php -f /path/to/x.php &

With nohup it'll keep running even if the user logs out.

The cron solutions in other answers will start a new instance each time they are run - not sure if you want that. However if the script dies and you want to restart it, then you will have to run a separate daemon that checks if it's running and if not, start it. You could make a simple script that does the check and starts running it, and then cron that script to run say every 5 minutes or however often you want.

Upvotes: 2

Related Questions