Belide Akhil
Belide Akhil

Reputation: 33

Reseting a variable value everyday at midnight in node js

I have a global var in my node js code. I need to reset its value to 1 everyday midnight at 12am. How is it done in node js? I have read certain articles about node scheduler. Does it work or there are any other ways?

Upvotes: 1

Views: 1976

Answers (2)

eol
eol

Reputation: 24555

Using node-schedule this should be straightforward. Define your job with the correct cron-tab and reset the variable to the default value in the scheduleJob-callback:

const schedule = require('node-schedule');
let yourVar = 12345;

const globalResetJob = schedule.scheduleJob('0 0 * * *', () => {
  yourVar = 1;
});

Upvotes: 0

jfriend00
jfriend00

Reputation: 707148

You can use a simple setTimeout() to schedule it yourself:

let myVar = 10;

function scheduleReset() {
    // get current time
    let reset = new Date();
    // update the Hours, mins, secs to the 24th hour (which is when the next day starts)
    reset.setHours(24, 0, 0, 0);
    // calc amount of time until restart
    let t = reset.getTime() - Date.now();
    setTimeout(function() {
        // reset variable
        myVar = 1;
        // schedule the next variable reset
        scheduleReset();
    }, t);
}

scheduleReset();

Any time your program starts, it can just call scheduleReset().

FYI, I lifted most of this code from a program I wrote (on a Raspberry Pi server) that restarts itself at 4am every night and that program has been doing that successfully for several years.

Upvotes: 1

Related Questions