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


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


 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.
}

php 超时

幻想万華鏡 10 years, 11 months ago

 set_time_limit()

这一个

神秘君17号 answered 10 years, 11 months ago

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

野原新之助 answered 10 years, 11 months ago


 // 设置闹钟信号处理,抛异常退出循环
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);
}

草莓甜甜酱 answered 10 years, 11 months ago

Your Answer