php - 为什么 php sleep() 会暂停所有脚本的执行?
问题描述
我正在尝试在 php 中实现简单的 longpolling,我的服务器代码如下所示:
if (!isset($_SESSION["lastResult"])) {
$_SESSION["lastResult"] = "";
}
while(true){
$sql = "SELECT * from table";
$result = mysqli_query($conn, $sql);
$array = [];
while ($row = $result->fetch_array()) {
do something and insert each element into $array;
}
$jsonRes = json_encode($array);
//if old array is different from the new one, that means information has been updated,
//so I need to echo new data to user.
if (strcmp($jsonRes, $_SESSION["lastResult"]) == 0) {
echo $jsonRes;
$_SESSION["lastResult"] = $jsonRes;
exit();
}
//If information hasn't changed, just sleep for 5 seconds and repeat next time.
sleep(5);
}
和客户端代码:
const waitForData = () => {
//this is just a js fetch function
getDataHTTP().then(res => {
this.setState({ itemsData: res });
waitForData ();
});
};
waitForData();
但是发生在我的网络选项卡中,我看到我的 getData php 脚本应该“挂起”,但它永远挂起,另一件事是我不能真正编辑网页上的任何其他数据,因为出于某种原因,我认为这是sleep()
功能,我所有的 php 脚本都停止工作,并且永远是“待定”。
提前致谢。
编辑:
只是为了记录,$_SESSION 变量有效,所有数据都在它应该在的地方。SQL 查询也是如此,它会正确返回所有内容。
编辑2:
除了最大执行时间外,我没有收到任何错误。
解决方案
看看你的代码:
while(true){ // do this FOREVER unless we break the loop
$sql = SELECT * from table; // I assume we always get all rows?
$result = mysqli_query($conn, $sql);
$array = [];
while ($row = $result->fetch_array()) {
// Do stuff
$array[] = $row;
}
// now array has all rows
$jsonRes = json_encode($array);
if (strcmp($jsonRes, $_SESSION["lastResult"]) == 0) {
echo $jsonRes;
$_SESSION["lastResult"] = $jsonRes;
exit();
}
// so just sleep 5 seconds and do it all over again
sleep(5);
}
在表中有一个日期时间列不是更容易吗,如果选择返回的更新时间行晚于上次运行的时间,那么选择 * 并返回?什么时候没有真正的循环?
推荐阅读
- python - 使用 Selenium 抓取 LinkedIn 个人资料
- javascript - JSON 无法获取值 [JS]
- c# - XUnit 跳过所有测试
- vue.js - 如果 Vue JS 数据对象发生变化,如何被动监控?
- excel - 在excel中选择多个单个单元格
- python - 我无法在 python 中使用 exec() 函数创建熊猫数据框
- cordova - 添加cordova fcm插件后的Gradle版本冲突
- python - 美丽的汤不返回任何东西
- java - 任何可以判断哪个输入参数字段未通过验证的 java http 请求验证库?
- xcode - 将 ceres-solver 构建为 Mac Catalyst 的静态库