Home » Nodejs » Running a function everyday midnight

Running a function everyday midnight

Posted by: admin November 30, 2017 Leave a comment

Questions:
walk.on('dir', function (dir, stat) {
    uploadDir.push(dir);
});

I am using Node, and i need make this function run everyday at midnight, this is possible?

Answers:

I believe the node-schedule package will suit your needs. Generally, you want so-called cron to schedule and run your server tasks.

With node-schedule:

import schedule from 'node-schedule'

schedule.scheduleJob('0 0 * * *', () => { ... }) // run everyday at midnight

Questions:
Answers:

There is a node package for this node-schedule.

You can do something like this:

var j = schedule.scheduleJob({hour: 00, minute: 00}, function(){
    walk.on('dir', function (dir, stat) {
       uploadDir.push(dir);
    });
});

For more info, see here

Questions:
Answers:

Is this a part of some other long-running process? Does it really need to be? If it were me, I would just write a quick running script, use regular old cron to schedule it, and then when the process completes, terminate it.

Occasionally it will make sense for these sorts of scheduled tasks to be built into an otherwise long-running process that’s doing other things (I’ve done it myself), and in those cases the libraries mentioned in the other answers are your best bet, or you could always write a setTimeout() or setInterval() loop to check the time for you and run your process when the time matches. But for most scenarios, a separate script and separate process initiated by cron is what you’re really after.

Questions:
Answers:

I use the following code:

function resetAtMidnight() {
    var now = new Date();
    var night = new Date(
        now.getFullYear(),
        now.getMonth(),
        now.getDate() + 1, // the next day, ...
        0, 0, 0 // ...at 00:00:00 hours
    );
    var msToMidnight = night.getTime() - now.getTime();

    setTimeout(function() {
        reset();              //      <-- This is the function being called at midnight.
        resetAtMidnight();    //      Then, reset again next midnight.
    }, msToMidnight);
}

I think there are legitimate use-cases for running a function at midnight. For example, in my case, I have a number of daily statistics displayed on a website. These statistics need to be reset if the website happens to be open at midnight.

Also, credits to this answer.