E
E
Ernest Faizullin2016-04-01 05:40:15
Node.js
Ernest Faizullin, 2016-04-01 05:40:15

Exact time on the server with an interval of 1 second?

I'm trying to get a "ticking" server with an exact or almost exact period of 1 second to get a relatively accurate time with an error of no more than 1 second. There is an example.com/timer
controller to which nodejs sends the current time with an interval of 1000ms. Then from the controller the time is output to the browser:

var request = require('request');

var requestLoop = setInterval(function() {
  var time = Math.round(+new Date()/1000);

  request({
    url: "http://example.com/timer",
    method: "POST",
    data: {time: time},
    followRedirect: false
  });
}, 1000);

The first week everything works fine, the time "ticks", but after a week the time in the browser starts to rush gradually and in a week the difference with the present time increases to about 4-5 seconds. It turns out that setInterval in this case works a little faster than 1000ms? Is it possible in some way to ensure that you always get the exact time on the server?
For several months I have been interested in this issue and knowledgeable people suggested that in order to get accurate periods of 1 second, you need to find a server with a frequency of a multiple of 60, but such things do not happen and everything is bad. But there are services on the Internet that display the exact time and it is never in a hurry. " Apparently, somehow it is necessary to smooth out the error in the intervals between requests, which accumulates over time. Any ideas?
UPD: in more detail: setInterval is constantly spinning on the nodejs server, sending requests to the timer controller, which is on laravel.
How the time is displayed in the browser: the timer controller pushes the time to clients on request (web socket), and on the client it is output in a readable format to the browser.
The problem is that setInterval after 1-2 weeks of work shows the time 4-5 seconds more than the current time

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Shidlovsky, 2016-05-03
@erniesto77

You have chosen the wrong technology (with an asynchronous "hammer" you are trying to synchronize the "nails").
Modern systems have learned to synchronize time quite well, so let the OS do it.
ps. Please note that the "deferred" call functions do not work accurately. The call to (setTime(fn, 100)) can happen after 100ms. or after 1200 (this depends on the workload of the main node.js loop).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question