Tuesday, 20 August 2013

Script with sleep() is slowing down server, causing Apache to crash

Script with sleep() is slowing down server, causing Apache to crash

I have a website that has messaging functionality between users. When a
user is logged in, I use jQuery.ajax() to call a PHP script to check for
new messages. To cut down on requests, my PHP script loops a call to the
check_new_messages() function and if there are no new messages, I call
sleep(5) inside the loop, so that it waits 5 seconds and then continues
the loop. I check how long the script has been executing by using
microtime() and if it exceeds 60 seconds, I return 0. The ajax will
receive this value and then call the script again.
function check_message_queue($user) {
$response = 0;
$msgs = 0;
$time_start = microtime(true);
while (!$msgs = check_new_messages($user)) {
sleep(5);
$time_end = microtime(true);
if ($time_end - $time_start >= 60)
return $response;
}
// has new messages
sleep(5);
return $response;
}
My php.ini has max_execution_time set to 120.
At first everything works OK, but when I refresh the page there is about a
10 second delay and sometimes I'll get the PHP error "Max execution time
of 30 seconds has been exceeded" followed by Apache crashing. My PHP
max_execution_time is definitely set to 120 seconds, so I'm not sure
what's going on.
I've never done anything like this before, so hopefully it's just some bad
coding on my part.
Here is my JavaScript:
var request_new_messages = function() {
$.ajax({
url: 'messages/checkqueue',
type: 'post',
contentType: 'application/x-www-form-urlencoded; charset=utf-8',
data: { id: 0 },
complete: function() { request_new_messages(); },
error: function(jqXHR, textStatus, errorThrown) { handle_error(); },
success:
function(data, textStatus, jqXHR) {
if (textStatus == "success") {
if (!isNaN(data)) {
var response = parseInt(data);
if (response > 0)
alert('You have ' + response + ' new messages.');
}
}
}
});
};

No comments:

Post a Comment