admin admin
admin admin

Reputation: 85

How can I setinterval with Nodej.s for a specific time of day?

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?

Upvotes: 1

Views: 186

Answers (1)

Mureinik
Mureinik

Reputation: 311978

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();
});

Upvotes: 2

Related Questions