Search code examples
phpajaxserver-sidelong-polling

How does facebook prevent exceeding max_execution_time in long polling empty responses?


So, how does facebook return 200 status code when there are no new message/update?

I tried long polling and it works. the only problem I am facing right now is that I am encountering 500 Internal Server Error (exceeded max_execution_time) when the polling is not returning anything.

I do not want to alter the "max_execution_time" of the poll, but what I want is to return a 200 OK status code even when there are no new messages/updates.

Edit:
I've read from various sources including stackoverflow (sorry I've read too many and could not quote all of it here) where it says that I should return an empty response to get a 200 status code.

Now, the new problem is:

How can I return an empty body response while there is no new message/update (while "while" loop is running and about to reach max_execution_time) to prevent 500 Internal server error (exceeded max_execution_time).

In a more simple term:
how to return empty response before while loop reaches timeout


Solution

  • Okay I've found a workaround, or a neat or rather nasty solution haha!

    A comment by a user named Adeel in this thread gave me the idea.

    What I did was to set a time for the future 30 seconds from now:

    $future = date("Y-m-d H:i:s", strtotime("+30 seconds"));
    
    while ($last_number < $new_number){
        $now = date("Y-m-d H:i:s");
        if($now == $future){
            break 1;
        }
    
        //some codes for iteration and updating $last_number in this while loop
    }
    
    echo json_encode();
    

    I do not know if this is the best way to achieve what I had in mind, but it is the only way that worked out so far.

    If you guys have better solutions, I would be glad to know.

    So in the end, I just had to break out of the loop haha how stupid cou