doudou0111 2016-08-20 10:02 采纳率: 0%
浏览 50

什么是更好的无限循环或ajax / setInterval梳子

I have to to react fast on a status change in my database table "soundboard". If the status is changed to 2, I want that my application will notice it.

So whats better, I created 2 examples one for an infinite loop and one for an ajax / setInterval script.

First the infinite loop:

<?php

// Settings & Connection
set_time_limit (0);
$data = array(
    "id"    =>  "",
    "file"  =>  ""
);
$db = new mysqli('p:localhost', 'username', 'password', 'database');

// Query 2 DB
$sql = "SELECT id, name, file FROM soundboard WHERE status = 2 LIMIT 1;";

while(TRUE) {
    $result = $db->query($sql);

    if($result->num_rows > 0) {
        // Fill $data here
        echo json_encode($data);

        break;
    }
    unset($result);

    sleep(5);
}
$db->close();
unset($db, $data, $sql);
exit;

?>

Or is this better for the perfomance?

<?php

// Settings & Connection
$data = array(
    "status"    =>  0,
    "id"        =>  "",
    "file"      =>  ""
);
$db = new mysqli('localhost', 'username', 'password', 'database');

// Query 2 DB
$sql = "SELECT id, name, file FROM soundboard WHERE status = 2 LIMIT 1;";
$result = $db->query($sql);

if($result->num_rows > 0) {
    // Fill $data here
}

$db->close();
echo json_encode($data);
unset($db, $data, $sql);
exit;

?>

I hope you can help me and understand what I am trying to do.

  • 写回答

1条回答 默认 最新

  • douyue5856 2016-08-20 10:27
    关注

    First of all, a infinite loop is always a risk. BUT if you have to do it I think that it is better If you are doing this in the client side:

    First of all, you have to take care of your server, because if someone block it... If a user block his PC, it is just a PC, just a User.

    Second, if you need a permanent open connection (like PHP infinite loop), probably you prefer to open a Socket Like in a PHP Chat program.

    About permormance, A Shocket it is the best solution (in my opinion).

    You can Check this link: https://www.sanwebe.com/2013/05/chat-using-websocket-php-socket

    评论

报告相同问题?

悬赏问题

  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行