I have a server with a web interface, through which a task is submitted to the server and the result is returned to the user as a web page. Sometimes the result is generated on the fly, sometimes it may take several hours. The result is written on disk and check_status function periodically checks whether the task is completed.
In the code given below it seems
while ($status == 0) {
sleep(x);
$status = check_status($pars);
...
}
hangs up the server for big tasks when the user waits until his or her task will be completed.
What would be the optimal solution to return the result to the user timely and not overload
the server with excessive requests?
Set up a limit in the loop and terminate it? Or are there modern advanced technologies to
handle these situations more efficiently?
$status = check_status($pars);
if ($status == 1) {
...
print $result;
}
else {
print $reference_to_future_result;
}
ob_flush();
flush();
while ($status == 0) {
sleep(30);
$status=check_status($pars);
if ($status == 1) {
...
change_page_content_to_result;
}
}
...
If open connections to your server is an issue, I would suggest periodically polling from the client side using AJAX. The client would check in every so often, and your server would return the status of your job in a simple HTTP response.
I would recommend building something using JavaScript’s
setInterval()and jQuery‘s AJAX functionality.