Running a function everyday midnight

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:

Answer

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
Answer

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

Answer

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.

Answer

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.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.