Print message at the right time

Viewed 97

next ... I have a code, and I want it to do a certain action every day at a specific time.

As I am learning JS, I believe I have to use a loop for this (I don't know), but I would like your help.

My code:

data = new Date
horas = data.getHours()
minutos = data.getMinutes()

if(horas === 11){
console.log('Okay!')
}

In this code (which is in the node), it only prints "okay" and rightly if I'm running at 11am. How do I run the code and only print it when the time is right? Example:

I execute the code at 11 am, but with the condition of if getHours () === 12, how can I make it print at the terminal when it is 12 pm?

2 Answers

As @h0r53 said, you'll need a setInterval call.

setInterval(() => {
  data = new Date()
  horas = data.getHours()
  minutos = data.getMinutes()

  if(horas === 11){
    console.log('Okay!')
  }
}, 60000)

This will run once every minute and log "Okay" whenever it's in the target hour. If you want it to only run once an hour you can change the timing or check for a specific minute as well.

Alternative solution with node-schedule:

const schedule = require('node-schedule');
 
const j = schedule.scheduleJob('0 11 * * *', function() {
  console.log('Okay!')
});

0 11 * * * is read as every 11:00 (11th hour and the first minute everyday)


OR

const schedule = require('node-schedule');

const rule = new schedule.RecurrenceRule();
rule.hour = 11;
rule.minute = 0;

const j = schedule.scheduleJob(rule, function(){
    console.log('Okay!')
});
Related