Home  >  Article  >  php教程  >  为PHP函数执行设置超时

为PHP函数执行设置超时

WBOY
WBOYOriginal
2016-06-13 11:31:42964browse

如何防止一个函数执行时间过长呢?在PHP里可以用pcntl时钟信号+异常来实现。

代码如下:

declare(ticks = 1);
    function a(){
    sleep(10);
    echo "a finishi\n";
}
function b(){
    echo "Stop\n";
}
function c(){
    usleep(100000);
}

function sig(){
    throw new Exception;
}

try{
    pcntl_alarm(1);
    pcntl_signal(SIGALRM, "sig");
    a();
    pcntl_alarm(0);
}catch(Exception $e){
    echo "timeout\n";
}

b();
a();
b();

  

原理是在函数执行前先设定一个时钟信号,如果函数的执行超过规定时间,信号会被触发,信号处理函数会抛出一个异常,被外层代码捕获。

这样就跳出了原来函数的执行,接着执行下面的代码。如果函数在规定的时间内,时钟信号不会触发,在函数结束后清除时钟信号,不会有异常抛出。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn