Home  >  Article  >  Backend Development  >  超时 - PHP 是否可以限制函数执行时间?

超时 - PHP 是否可以限制函数执行时间?

WBOY
WBOYOriginal
2016-06-06 20:41:54942browse

PHP 是否可以限制函数执行时间,以使下列伪代码的功能得以实现?

<code>foreach ($jobs as $job) {
    try {
        run($job);
    } catch (TimeoutException $e) {
        printf("Timeout: %s\n", $e->getMessage());
        continue;
    }
}

function run($job) {
    // ssh, HTTP request, Connect DB etc.
}
</code>

回复内容:

PHP 是否可以限制函数执行时间,以使下列伪代码的功能得以实现?

<code>foreach ($jobs as $job) {
    try {
        run($job);
    } catch (TimeoutException $e) {
        printf("Timeout: %s\n", $e->getMessage());
        continue;
    }
}

function run($job) {
    // ssh, HTTP request, Connect DB etc.
}
</code>

<code>// 设置闹钟信号处理,抛异常退出循环
declare(ticks = 1);
pcntl_signal(SIGALRM, function(){throw new Exception('process_timeout');});

// 设置闹钟,5秒超时
pcntl_alarm(5);

$jobs = array_fill(0, 1000, 'job');
foreach ($jobs as $job) {
    try {
        run($job);
    } catch (Exception $e) {
        printf("Timeout: %s\n", $e->getMessage());
        exit;
    }
}

function run($job) {
    // ssh, HTTP request, Connect DB etc.
    sleep(1);
}
</code>

推荐你一个框架swooole
看你代码就是要处理一个花费时间比较长的任务
swoole里的task,提交过去一个任务,立即返回,任务在后台自动运行,不用关注运行时间
设置了 set_time_limit() 会使任务无法完成

<code>set_time_limit()
</code>

这一个

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