Running a function everyday midnight

后端 未结 4 1477
难免孤独
难免孤独 2020-12-05 04:42
walk.on(\'dir\', function (dir, stat) {
    uploadDir.push(dir);
});

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

相关标签:
4条回答
  • 2020-12-05 05:05

    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
    
    0 讨论(0)
  • 2020-12-05 05:18

    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.

    0 讨论(0)
  • 2020-12-05 05:26

    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

    0 讨论(0)
  • 2020-12-05 05:30

    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.

    0 讨论(0)
提交回复
热议问题