We are going to an easy solution. Run a task (which is inside a function) that runs on a specific date and time:
"use strict";
function tarea(){
console.log('acá va la tarea', new Date());
}
function lanzarElDia(momento, tarea){
console.log('lanzado',new Date());
console.log('para ser ejecutado en',momento);
setTimeout(tarea, momento.getTime()-(new Date()).getTime());
}
lanzarElDia(new Date('2016-06-10 20:29'), tarea);
Run every day at a certain time
If instead we want to execute a task every day at 21:10 we must calculate how many milliseconds are missing for that moment:
"use strict";
function tarea(){
console.log('acá va la tarea', new Date());
}
function lanzarSiempreALaHora(hora, minutos, tarea){
var ahora = new Date();
console.log('lanzado',ahora);
var momento = new Date(ahora.getFullYear(), ahora.getMonth(), ahora.getDate(), hora, minutos);
if(momento<=ahora){ // la hora era anterior a la hora actual, debo sumar un día
momento = new Date(momento.getTime()+1000*60*60*24);
}
console.log('para ser ejecutado en',momento);
setTimeout(function(){
tarea();
lanzarSiempreALaHora(hora,minutos,tarea);
},momento.getTime()-ahora.getTime());
}
lanzarSiempreALaHora(21,10, tarea);
When the date of the machine is changed
The problem is when you change the date or time of the machine. To do this, you should have a timer that controls every minute (or every x seconds, according to the precision you want) if you have reached the desired time.
Attention
There are no guarantees (with setTimeout or with any cron) that something will be executed exactly on a schedule, the only thing that is known is that it will be executed after the appointed time and as soon as possible close to that time.