grautur
grautur

Reputation: 30485

How to to poll a server that updates every 1 second?

I have a server at http://foobar that returns a JSON object containing information about things that happened in the past second, e.g., something like

{
    time: 2011-06-08 05:07:33,
    total: 235324,
    average: 1233
}

What's the best way to poll this server so that I get every update? I'm guessing I don't want to just poll the server, sleep for 1 second, and then poll again (since the polling might take some time and cause things to get delayed, so I might miss some updates). Should I do something instead like sleep for only 0.5 seconds, poll the server, and then check whether the JSON object I receive has a different timestamp from the last JSON I received?

(I'm doing this in Java, by the way, though I don't think the language really matters.)

Upvotes: 1

Views: 1783

Answers (2)

Bohemian
Bohemian

Reputation: 425043

You can use the "blocking pull" pattern (don't know what it real name is):

  1. Client polls and the server asking for info
  2. Server waits until it has new info (which may be no time at all if info is ready)
  3. Server responds with info
  4. Goto step 1.

The advantage of this pattern is

  1. Comms is kept to a minimum
  2. There is no lag between new info being available and you being sent it (with polling, there is an average lag of 50% of the poll frequency)

The disadvantage is that the client is almost always in a blocked state. This may not suit all client applications

Upvotes: 1

Zian Choy
Zian Choy

Reputation: 2894

If you need to get every update, the server should be pushing the updates to you instead of going the other direction.

For example, you should look into setting up a stream between the client and server so that the server can send event notifications to the client.

Upvotes: 4

Related Questions