开发者

PHP loop that runs beyond browser disconnection?

开发者 https://www.devze.com 2022-12-21 22:13 出处:网络
I want to have a simple PHP script that loops to do something every ten 开发者_如何学JAVAminutes.It would be hosted offsite, and I would activate it via my browser.I don\'t have access to the server o

I want to have a simple PHP script that loops to do something every ten 开发者_如何学JAVAminutes. It would be hosted offsite, and I would activate it via my browser. I don't have access to the server other than my web space, so 'cron' as such isn't an option.

(I'm happy to have this stop after a certain time or number of job cycles. I just need it to continue running after I point the browser away from the page script.)

Is such a thing possible? Thanks.


It's possible, see ignore_user_abort():

set_time_limit(0);
ignore_user_abort(true);

while (true) // forever
{
    // your code
}

You can use this two functions with a combination of sleep(), usleep(), time_nanosleep() or even better - time_sleep_until() to achieve a CRON-like effect.


PHP scripts timeout after a certain amount of time - they're not designed for long-running programs. You'll have to find some way to prod it every ten minutes.

Have a look at set_time_limit.

This is from the above page:

You can do set_time_limit(0); so that the script will run forever - however this is not recommended and your web server might catch you out with an imposed HTTP timeout (usually around 5 minutes).


Maybe you can write another script on a computer which you have access and then make that script request the other one periodically.


Yop can look at pnctl_fork.


Here's a hack for your problem:

// Anything before disconnecting, but nothing to be output to the client!
ob_end_clean();
header('Connection: close');
ob_start();
// Here you can output anything before disconnecting
echo "Bla bla bla";
$outsize = ob_get_length();
header('Content-Length: '.$outsize);
ob_end_flush();
flush();
// Do your background processing here
// and feel free to quit anytime you want.


A way to do this might be to launch a new php process from the web page, e.g.

<?php

exec("php script_that_runs_for_a_while.php > /dev/null");

?>

Adding the /dev/null means (on a linux system) that your script will complete, rather than waiting for the execution to finish.

So then that script that launches can do whatever it likes, since it is basically just a new process running on the server.

Note that at the start of your long running script, you will want to use the set_time_limit function to set the max execution time to some large value.

0

精彩评论

暂无评论...
验证码 换一张
取 消