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 是否可以限制函数执行时间,以使下列伪代码的功能得以实现?
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.
}
// 设置闹钟信号处理,抛异常退出循环
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);
}
推荐你一个框架swooole
看你代码就是要处理一个花费时间比较长的任务
swoole里的task,提交过去一个任务,立即返回,任务在后台自动运行,不用关注运行时间
设置了 set_time_limit() 会使任务无法完成
set_time_limit()
这一个