php实现轮询
PHP实现轮询的基本方法
轮询在PHP中通常用于检查数据更新或执行定时任务。以下是一种基础的实现方式:
<?php
// 设置脚本执行时间无限制
set_time_limit(0);
// 轮询间隔时间(秒)
$interval = 5;
while(true) {
// 执行需要轮询的操作
checkForUpdates();
// 等待指定间隔
sleep($interval);
}
function checkForUpdates() {
// 这里放置检查更新的逻辑
// 例如检查数据库、API或文件变化
}
使用数据库检查的轮询示例
当需要检查数据库记录变化时:

<?php
$db = new PDO('mysql:host=localhost;dbname=test', 'user', 'password');
$lastId = 0;
while(true) {
$stmt = $db->prepare("SELECT * FROM messages WHERE id > ?");
$stmt->execute([$lastId]);
$messages = $stmt->fetchAll();
if(!empty($messages)) {
// 处理新消息
$lastId = end($messages)['id'];
}
sleep(5);
}
优化性能的轮询技术
为避免服务器资源过度消耗:
<?php
// 使用连接保持和缓存控制
header('Cache-Control: no-cache');
header('Content-Type: text/event-stream');
header('Connection: keep-alive');
while(true) {
$hasUpdate = checkUpdateFunction();
if($hasUpdate) {
echo "data: " . json_encode($hasUpdate) . "\n\n";
ob_flush();
flush();
}
// 较短的间隔提高响应速度
usleep(100000); // 0.1秒
}
结合前端实现的完整方案
后端PHP轮询脚本:

<?php
// poll.php
$lastCheck = $_GET['lastCheck'] ?? 0;
$currentTime = time();
// 模拟数据变化检查
if($currentTime - $lastCheck > 10) {
$response = ['updated' => true, 'data' => getNewData()];
} else {
$response = ['updated' => false];
}
header('Content-Type: application/json');
echo json_encode($response);
前端JavaScript调用:
function startPolling() {
let lastCheck = 0;
const poll = () => {
fetch(`poll.php?lastCheck=${lastCheck}`)
.then(response => response.json())
.then(data => {
if(data.updated) {
// 处理更新
lastCheck = Date.now() / 1000;
}
setTimeout(poll, 5000);
});
};
poll();
}
注意事项
- 长时间运行的脚本需要设置
set_time_limit(0) - 考虑使用数据库的
LAST_INSERT_ID()或时间戳字段优化查询 - 生产环境建议考虑WebSocket或Server-Sent Events(SSE)替代频繁轮询
- 确保适当的休眠间隔避免服务器过载
替代方案建议
对于需要实时通信的应用:
- WebSocket提供全双工通信
- Server-Sent Events(SSE)适合服务器到客户端的单向推送
- 消息队列系统如Redis Pub/Sub
这些方法相比传统轮询能显著降低服务器负载和提高响应速度。






