tags:

views:

81

answers:

6

I want to have a simple PHP script that loops to do something every ten minutes. 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.

A: 

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).

Skilldrick
A: 

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

Sinan
Google AppEngine would be one choice, there are other questions here on SO that describe how to set up a cron job there that calls your script.
Wim
Thanks for showing me this, I never knew about it.
A: 

Yop can look at pnctl_fork.

Kuroki Kaze
+1  A: 

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.

Alix Axel
I would say that ignore_user_abort should be used only when you need to guarantee atomicity in some non-db-related action. I would think it would block the Apache thread/child process until the script completes?
Kazar
That's what the OP is asking for, right?
Alix Axel
All of these answers have been extremely helpful.So far I've had a successful set of test runs with this.
A: 

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.
TheOnly92
A: 

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.

Kazar