简体   繁体   中英

PHP: Limit execution time per function

foreach ($arr as $k => $v)
{
    $r = my_func($v);   

    $new[$k] = $r;
}

How do you do it so that $r will return false if my_func() takes more than 10 secs to execute, else (if it took less than 10 secs) it will return true;

Additional info: my_func() actually reads a URL, sometimes it takes to long. I want it to return false if it takes more than 10 secs.

You cannot limit execution time by function in PHP. However, do not despair: if as you mentioned your function reads URL, you could use curl extension, which has options set options via curl_setopt , as following:

CURLOPT_TIMEOUT The maximum number of seconds to allow cURL functions to execute. CURLOPT_CONNECTTIMEOUT The number of seconds to wait while trying to connect.

Using these you could limit the actual time spent on the URL processing with curl.

You could also use http extension which also allows you to do http connections and has timeout options .

Finally, you could use context options to file_get_contents :

$opts = array('http' =>
    array(
        'timeout' => 1.5 // 1.5 seconds
    )
);

$context = stream_context_create($opts);

$result = file_get_contents('http://example.com/getdata.php', false, $context);

If my_func reads a URL and you just don't want it to take longer than a given timeout period, if you use the right URL functions, you should be able to specify that timeout and have the call fail if it takes longer than that.

If you were using cURL, you could use curl_multi_exec to get this behavior somewhat manually, or just specify the timeout and then the function can return false.

Example:

function my_func($url)
{
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10); // timeout after 10 seconds

    // .. set other options as needed
    $result = curl_exec($ch);

    if ($result === false) {
        // timeout or other failure
        return false;
    }
}

Now the function won't run longer than roughly 10 seconds due to the timeout. You can also use curl_errno() to check for a timeout:

if (curl_errno($ch) == 28) {
    // timeout was exceeded
}

Do something like:

foreach ($arr as $k => $v)
{
    $before = time()

    $r = my_func($v); 

    $after = time();

    $timeDelta = $after - $before;
    if($timeDelta < 10){
      $r = true;
    }
    $new[$k] = $r;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM