Domanda

I have a function that I need to timeout and output an error message.

I have found the set_time_limit() function, but I dont think I am using it right.

I have tried...

... some code ...

set_time_limit(12);

$client->sendHttp(URL, TIMEOUT_CONNECT, TIMEOUT_READ);

if (set_time_limit(12) != true){
    $_SESSION['Message'] = "Transaction Timed Out!";
}
... some code ...

That's the best I could come up with but it doesn't work. Can you suggest anything?

È stato utile?

Soluzione

set_time_limit limits the scripts time, the script all together will end after that amount of time no code will be executed after that

$client->sendHttp should return false, null if a timeout has been reached, read the documentation on that function to see what it will actually return.

Altri suggerimenti

Normally if the script timeout, the web server stops it and return an error while You have only a little chance of handling it by Yourself - by defining shutdown function.

But You could use a simple function of Your own, like this one:

function check_timeout($start) {
    if(microtime() <= $start + MAX_EXECUTION_TIME)
        return true;

    return false;
}

while the MAX_EXECUTION_TIME constant would be defined somewhere like

define('MAX_EXECUTION_TIME', 10000); // 10 seconds

Now somewhere in Your code You could do:

// some code...

$start = microtime();

foreach($array as $key => $value) {
    if(check_timeout($start)) {
        // do something
    } else {
        // set HTTP header, throw exception, etc.
        // return false; // die; // exit;
    }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top