开发者

How do I skip a process or function if it doesn't give a result within fixed time?

In PHP I have seen that if a certain process or function isn't completed then the entire application which includes that function get delayed due to that.

Say there is a search function which returns lots of result which includes more than 20 functions. An "x" function is taking too much time, hence the result page is getting delayed due to that. My question is how do I fix a time limit to "X" function, say 2 seconds, and if it isn't complete within that time then "X" functio开发者_StackOverflown should be skipped.

Is there any way to do that or better?


So, if you're talking about file_get_contents (why didn't you say that right away?) you may specify a timeout using stream contexts:

$ctx = stream_context_create(array(
    'http' => array(
        'timeout' => 10
        )
    )
);
file_get_contents("http://example.org/", 0, $ctx);

See HTTP context options.

If using curl use curl_setopt for CURLOPT_TIMEOUT.

curl_setopt($curl, CURLOPT_TIMEOUT, 10);

This will set timeout to ten seconds.


Not a direct answer to your question, but perhaps a possible solution to your problem:

Are the search results of the different sites mixed in one big result?

If not, I would use ajax to load the different sections / results simultaneously, showing the sub-results as soon as they become available.

If you want to mix all sub-results, you could still do the same storing the sub-results in a session and generating your final output when all 20 are known or when a certain time has passed.

This does depend heavily on javascript however...

Edit: jquery example:

Using jquery you can load the different results in different div's:

javascript

/* start loading results when the document is loaded */
$(document).ready(function() {
    $("#results01").load("http://www.mysite.com/page_results_01.php");
    $("#results02").load("http://www.mysite.com/page_results_02.php");
    ...
    $("#results20").load("http://www.mysite.com/page_results_20.php");
});

html

<div id="results01">Loading results from page 01 ...</div>
<div id="results02">Loading results from page 02 ...</div>
...
<div id="results20">Loading results from page 20 ...</div>

Emtpy div's don´t show, so you can get rid of the text if you don´t want it...


You may have a look at tick functions and declare. So you execute the tick function say every 10 ticks and check execution time. But I have no idea how the tick function may abort the further execution of the function...


The canonical way to handle something like this without resorting to a thread pool is an alarm signal. Here's what I was able to find in a quick search of the PHP docs:

http://php.net/manual/en/function.pcntl-signal.php

http://php.net/manual/en/function.pcntl-alarm.php

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜