I'm writing a chat application for joomla (apache server) and use this construction to emulate long-polling (server side):
function get_messages($last_id) {
$time = time();
while((time() - $time) < 25) {
$sql = 'SELECT * FROM #__messages WHERE `id` >'.intval($last_id);
$db->setQuery($sql);
$rows = $db->loadAssocList();
if (count($rows)>0) {
echo 'JSON STRING HERE';
} else {
flush();
}
usleep(5000000);
}
}
How Can I optimize this part of code. Should I use infinite looping or should I avoid while construction? P/S: I know Apache is not best choice to write chat app for and node.js is better.
Thanks!
Infinite loops are never a good idea because they hammer your server resources. You are better off having JS providing the intermittent polling to your get_messages function. Use a timeout and embed the script on any page that shows the messages.