user3998237
user3998237

Reputation:

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?

Upvotes: 47

Views: 66422

Answers (4)

wap300
wap300

Reputation: 2780

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

Installation:

npm i node-schedule --save

Upvotes: 101

TinkerTank
TinkerTank

Reputation: 5815

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.

Upvotes: 32

Donal
Donal

Reputation: 32823

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

Upvotes: 22

Jason
Jason

Reputation: 13766

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.

Upvotes: 4

Related Questions