Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free.

Scenario

To deliver instant notifications to the client, I'm sending an AJAX request to a PHP page that checks if there are new notifications: if there are, it outputs them, otherwise it sleeps for 10 seconds before trying again, so it has a basic structure similar to the following one.

<?php
$max_attempts = 10000;
for($i=0;$i<=$max_attempts;$i++){
    check_new_notifications(); //checking notifications in an sql database
    if(new_notification){
      echo $notification;
      break;
    }
    else{
      sleep(10);
    }
}
?>

What is missing

While this is great for the client, as it doesn't have to send a request every 10 seconds, but just one, I can't find a better way for the server than to check every 10 seconds if there are new notifications.

My question

What solution could I adopt in order to avoid the server to constantly check for new notifications?

share|improve this question
1  
Turn the problem on its head--use something like SignalR to push notifications down to waiting clients. –  mgw854 Jul 29 at 17:49
    
@mgw854 thanks for your suggestion –  Stubborn Jul 29 at 17:59

1 Answer 1

up vote 1 down vote accepted

You can:

Use polling

However, think about sending a request every 10 seconds.
By using your suggested approach, you are keeping a long connection to the server, which is in turn keeping a busy process/thread. If this is used only by you, it's fine. If it's meant to be used by many users, it's a huge waste of resources, since the server will be busy doing nothing 99% of the time.

Use Websockets

This is the thing you need.
Websockets provide a direct and continous TCP communication between the browser and your server. Check out Ratchet, that's a great PHP library for websockets on the server side.

Use an external service

There are services like Pusher which also utilize websockets. However, you don't need a socket server yourself, but send them an event from your backend. Then their service pushes new data to your browser.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.