SRR
SRR

Reputation: 1748

Run a function once every 60 secs

I have a function that performs a database backup. I want this function to be run once every 24 hours. The way I've come up with to do this is shown below:

  const backupTime = '7:10'
  setInterval(()=>{
    const d = new Date().toString();
    const currentTime = d.substr(16,5); //24hr time
    if(currentTime === backupTime){
      //backup db
    }
  },60000)

This works, but if the user sets a backup time at 07:10 then the function will run on the second of the minute that the call to setInterval was made. I.e if it was made at 7:09:59 and the timeout is 60s then setInterval will run at 7:10:59 and not 7:10:00 which doesn't make for a good UX in terms of notifying the user a backup is happening and the like.

Is there anyway I can get it to run at exactly the time specified?

Upvotes: 0

Views: 91

Answers (1)

SoftDev
SoftDev

Reputation: 559

setInterval or setTimeout is not reliable for exact moment (especially if you count ms). Of course your requirement here allows 1- sec offset I guess. So the solution can be the following

  const backupTime = '7:10'
  let justFired = false;
  setInterval(()=>{
    const d = new Date().toString();
    const currentTime = d.substr(16,5); //24hr time
    if(currentTime === backupTime && !justFired){
      justFired = true;
      //backup db
    } else if (currentTime !== backupTime && justFired) {
      justFired = false;
    }
  },1000) // call every second

Upvotes: 1

Related Questions