Home > Software engineering >  How can I setinterval with Nodej.s for a specific time of day?
How can I setinterval with Nodej.s for a specific time of day?

Time:09-03

I have the following function that runs every hour but I would like it to run once per day at 3 AM:

setInterval(async () => {
    await updateData();
}, 1000 * 60 * 30);

How can I achieve this?

CodePudding user response:

setInterval doesn't have this functionality directly. You could play around with date math to make this happen, but honestly, the easiest approach would probably be to use a thrid-party that does this for you, like node-cron.

First, you'd need to install it:

npm install node-cron

Then, in your code:

cron = require('node-cron'); 
cron.schedule('0 3 * * *', async () => {
    await updateData();
});
  • Related