1

I implemented heartbeat as the following

$.ajax({
    cache:false,
    timeout:8000,  
    type:"POST",
    url:"someurl.php",
    data:allFormValues,
    error:function(){ alert("some error occurred") },
    success:function(response){ //call some functions  }
   });

and in the server side

$time = time();
        while(!proccessServer() && (time() - $time) < 60 )
        {
            sleep(5);
        }

and simply it call a function if it returns false the loop will sleep for more 5 seconds and then check but the problem is this thing is eating my resources CPU and this was only when 5 users testing it

I used before this

window.setInterval(function(){
  //I call a function here 
}, 5000);

but also it was eating the resources because of many requests

and maybe my app have 100K online at the same time also I am not thinking about using websockets because of browsers compatibility What do you suggest to solve this ? any help is appreciated

Seder
  • 2,735
  • 2
  • 22
  • 43

2 Answers2

2

Your web server (Apache?) will use one thread until the request completes, which eats resources. AND you are using a PHP process for each visitor, just waiting. PHP is not very suitable for such solutions. You should look at other technologies if you want to do Comet. For example node.js.

You could also switch to NGiNX as web server, and use NGiNX_HTTP_Push_Module from http://pushmodule.slact.net/ for you application, and then stay with PHP. NGiNX will then accept the connection from your visitor and then wait for your code to push data to NGiNX. It might work for you, depending on what exactly you want to do.

Alfred Godoy
  • 1,045
  • 9
  • 19
1

The problem here is that you are letting the server sleep and retry. that itself is resource intensive. use it wisely.

what you should do is to poll the server in longer intervals, and have the server reply with a status like "done" or a "fail". after that, let JS determine the reply and do the retry - not PHP.


alternatively, you can use the new HTML5 sockets so that you have a persistent two-way connection from client to server. the server can push new content to the client without the client asking for it everytime.

Joseph
  • 117,725
  • 30
  • 181
  • 234