php 超时的实现
设置脚本最大执行时间
在 PHP 中,可以通过 max_execution_time 指令控制脚本的最大执行时间(秒)。修改方式如下:
- php.ini 配置:
max_execution_time = 30 // 全局设置为30秒 - 运行时动态设置:
ini_set('max_execution_time', 10); // 当前脚本设置为10秒
使用 set_time_limit 函数
动态调整脚本剩余执行时间(从调用时刻开始重新计时):
set_time_limit(20); // 重置为20秒
注意:set_time_limit 可能受安全模式限制,需确保环境允许。
实现分段超时控制
通过检查已用时间手动终止长耗时操作:
$startTime = time();
$maxDuration = 5; // 允许最长5秒
while (true) {
if (time() - $startTime >= $maxDuration) {
throw new Exception("Operation timed out");
}
// 继续执行任务
}
异步任务与超时处理
使用 pcntl 扩展实现子进程超时(需安装扩展):
$pid = pcntl_fork();
if ($pid == -1) {
die("Fork failed");
} elseif ($pid) { // 父进程
pcntl_wait($status); // 等待子进程
} else { // 子进程
sleep(10); // 模拟耗时操作
exit(0);
}
HTTP 请求超时设置
通过 cURL 或 stream_context_create 控制外部请求超时:
// cURL 示例
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://example.com");
curl_setopt($ch, CURLOPT_TIMEOUT, 5); // 5秒超时
// Stream 上下文示例
$ctx = stream_context_create([
'http' => ['timeout' => 3] // 3秒超时
]);
file_get_contents("http://example.com", false, $ctx);
数据库查询超时
部分数据库驱动支持超时参数(如 MySQLi):
$mysqli = new mysqli("localhost", "user", "pass", "db");
$mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 2); // 连接超时2秒
注意事项
- Web 服务器(如 Nginx/Apache)可能有额外超时配置,需同步调整。
- 长时间任务建议移至队列系统(如 RabbitMQ)异步处理。
set_time_limit不影响系统调用(如文件操作、网络请求)。







