Reputation: 1200
for example I do have 5 PHP functions on a page which execute when loading. each functions has its own processing time and some of them take more time sometimes to complete the task. hence the total loading time of the said page is slow.
my question is how do I control execution time for each script and set time limit for the same. I am aware that there is an in built function in PHP called set_time_limit();
but it gives fatal error if time is beyond the maximum limit...
Upvotes: 2
Views: 2159
Reputation: 154523
The easy way would be to call set_time_limit(0);
but that only works if you have safe_mode
Off.
My approach to this would be to use register_shutdown_function
:
function one() {
register_shutdown_function('two');
/* do stuff */
}
function two() {
register_shutdown_function('three');
/* do stuff */
}
function three() {
/* do stuff */
}
one();
This doesn't seem to work with PHP 5.3.1, I guess it's because of the changes implemented in PHP 4.1.0:
The shutdown functions are now called as a part of the request. In earlier versions under Apache, the registered shutdown functions were called after the request has been completed.
An alternative could be the use of pcntl_fork
, or you can just issue another request (with file_get_contents
for instance), and call ignore_user_abort
on the requested scripts.
Upvotes: 1
Reputation: 2446
From what your question says, I'm assuming that you have 5 functions in a single PHP file (script), executing, and if one of them executes for too long, it should be skipped.
The only way you can skip functions is to poll the time every once in a while.
function myFunction($someVar) {
$startTime = time();
$timeLimit = 10; // Let's say, time limit is 10 seconds
while ($blah_blah == true) { // Some loop or code that takes a long time
// Do some work
if (time() - $startTime > $timeLimit) return; // Time's up!
}
// Done
return;
}
Note that the function will only return at points where it checks if the time's up, and you have to manually place the points where you check if the time's up. This check does have some overhead, so try not to place it everywhere.
Please comment if I misinterpreted your question.
Upvotes: 1