0

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.

matteok
  • 2,189
  • 3
  • 30
  • 54

1 Answers1

1

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()
smokiespartakus
  • 176
  • 3
  • 14
  • do you mean a session as in "session_start()" then yes I am using one. – matteok Nov 06 '12 at 11:04
  • Yes - if you use session_start() it's my experience that you need to run session_write_close() somewhere before the loop, otherwise the script will choke. session_write_close() will stop you from changing stuff in the session, so if you have to, use session_start() before doing so and session_write_close() again after. – smokiespartakus Nov 06 '12 at 16:47
  • So if I have about 10 to 15 clients at a time polling content which would be 30 to 45 mysql SELECT requests per second I won't have to worry? – matteok Nov 06 '12 at 18:16
  • 10-15 clients shouldnt be a problem;o) – smokiespartakus Nov 06 '12 at 22:17