matteok
matteok

Reputation: 2189

Is this a legitimate long polling approach?

Is this PhP script a legitimate approach to long polling or is this to heavy on the server?

$FoundNewContent = false;

$tokens = array();

while(!$FoundNewContent) {
    usleep(300000);
    clearstatcache();
    $SQL1 = "SELECT * FROM tokens WHERE  ID > ".$_GET['tokenID'];
    $result1 = mysql_query($SQL1);
    while($row1 = mysql_fetch_array($result1, MYSQL_ASSOC)) {
        array_push($tokens, $row1);
        $FoundNewContent = true;
    }
}

// Parse XML array    

flush()

I am calling this script via Ajax.

Upvotes: 0

Views: 136

Answers (1)

smokiespartakus
smokiespartakus

Reputation: 176

Depends on your server setup - It should work fine as long as you don't use session, but if there are too many connections at a time it might stall the server.

Also I would add a time limit where it returns nothing and restarts the polling. Otherwise the script could run forever if no data is added and the server timeout is set to unlimited. I usually add a 30 sec limit.

Something like:

$FoundNewContent = false;
$tokens = array();
$time = time();
while(!$FoundNewContent) {
  usleep(300000);
  clearstatcache();
  $SQL1 = "SELECT * FROM tokens WHERE  ID > ".$_GET['tokenID'];
  $result1 = mysql_query($SQL1);
  while($row1 = mysql_fetch_array($result1, MYSQL_ASSOC)) {
    array_push($tokens, $row1);
    $FoundNewContent = true;
  }
  if($time<time()-30) break;
}
flush()

Upvotes: 1

Related Questions