Home > php教程 > php手册 > body text

为PHP函数执行设置超时

WBOY
Release: 2016-06-13 11:31:42
Original
1007 people have browsed it

如何防止一个函数执行时间过长呢?在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();
Copy after login

  

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

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

source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!