-1

How can i make this run every day at 8AM not just today at 8AM

var timeIsBeing936 = new Date("04/13/2021 08:00:00 AM").getTime()
   , currentTime = new Date().getTime()
   , subtractMilliSecondsValue = timeIsBeing936 - currentTime;
   setTimeout(getValue, subtractMilliSecondsValue);
Filur
  • 11
  • 2
  • 2
    Does this answer your question? [In JavaScript, how can I have a function run at a specific time?](https://stackoverflow.com/questions/24741530/in-javascript-how-can-i-have-a-function-run-at-a-specific-time) – Sudhir Ojha Apr 14 '21 at 06:55

3 Answers3

0

Idealy instead of running a javascript file forever, itd be better to use CRON jobs. Otherwise you can use hour, mins and seconds and check to see if its 8AM exact every second.


   var today = new Date();
   var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();

   setInterval(() => {
       time === "8:00:00" ? /* do something */ : null
   }, 1000);

cyw
  • 520
  • 1
  • 4
  • 14
0

You can use the node-cron package.

Docs: https://www.npmjs.com/package/node-cron

You can use it like this:

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

cron.schedule('8 0 * * *', () => {    // '8 0 * * *' => Run function every day at 8AM
   yourFunction();
});

NeNaD
  • 18,172
  • 8
  • 47
  • 89
0

You can make setTimeout "recursive" (it is not technically recursion), to call the scheduler function again after the previous is triggered.

Note: this is a pure JS solution, so it will work on every environment, but as setTimeout is inaccurate, this isn't the best option if you need high accuracy.

function onTime(cb, h = 0, m = 0, s = 0, ms = 0){
  let id
  void function r(){
    let timeUntilNextOccurrence = new Date().setHours(h, m, s, ms) - Date.now()
    if(timeUntilNextOccurrence <= 0)
      timeUntilNextOccurrence += 86400000
    id = setTimeout(() => {
      cb()
      r()
    }, timeUntilNextOccurrence)
  }()
  return function cancel(){
    clearTimeout(id)
  }
}

const cancel = onTime(() => console.log("It's 8 am!"), 8, 0, 0)

You can cancel it using the function it returns.

FZs
  • 16,581
  • 13
  • 41
  • 50