For JavaScript and NodeJS, there are n libraries that are robust in Cron style, such as node-cron . But they are complex for simple situations, they are heavy to download in the browser or require additional dependency on NodeJS, which makes them impractical in simpler cases.
I want to create a function that can:
- Accept the second, minute, and hour when the routine is ready to provide new data.
- Check what hours are now on the client, and schedule the start of
setInterval
for the first time the server has new data. - Set the interval of
setInterval
to exactly the period between server updates. - Run in NodeJS environment and modern browsers and in IE8. If you do not know how to test in NodeJS, I'll test it for you .
- There should be no additional dependency. No jQuery or NodeJS package.
- The code should accept a type interval parameter, try again in x seconds , and pass a callback to the executed function so that if it returns exactly
false
, it will try again until it returnstrue
or arrive at the time of the next standard execution. It considers that the server may fail and always return error, but the client should avoid overlapping additional attempts!
Real Use Example
The code below is responsible for synchronizing a table from a database with the browser or task NodeJS run
/**
* Sincroniza o cliente com dados do banco de dados. Caso os dados sejam
* diferentes dos que o cliente já possuia antes, passa ao callback true
* do contrário, se percebeu que o servidor ainda não atualizou os dados
* retorna false
*
* @param {Function} [cb] Callback. Opcional
*/
function sincronizar(cb) {
var conseguiuSincronizar = false;
// Executa uma rotina de sincronização de dados
cb && cb(conseguiuSincronizar);
}
However, the database is only updated once every 15 minutes, that is, in minutes 0
, 15
, 30
, 45
time.
As saving to database may take some time, this routine would have to run every 15min
and a few seconds of delay, for example, every 15min5s
.
The problem when using setInterval
is that to update every 15min, runs the risk of when the browser or the NodeJS task is initialized, there is a delay between the time when the client could obtain new information and the time where it is available. Setting setInterval
over a period of less than 15min would cause data loss.
Bootstrap
Below is a bootstrap of how the simplest example could be made.
function cron (cb, s, m, h) {
var start = 0, interval = 0;
/* Logica para calculo de start e interval aqui */
setTimeout(function () {
setInterval(cb, interval);
}, start);
}