每天午夜运行一个功能

29 javascript node.js

walk.on('dir', function (dir, stat) {
    uploadDir.push(dir);
});
Run Code Online (Sandbox Code Playgroud)

我正在使用Node,我需要让这个功能每天午夜运行,这可能吗?

wap*_*300 55

我相信node-schedule包将满足您的需求.通常,您希望所谓的cron计划和运行您的服务器任务.

使用节点计划:

import schedule from 'node-schedule'

schedule.scheduleJob('0 0 * * *', () => { ... }) // run everyday at midnight
Run Code Online (Sandbox Code Playgroud)

  • 谢谢!我不知道为什么,但是此程序包有效,而其他程序则无效。<3 (2认同)

Don*_*nal 17

有一个节点包node-schedule.

你可以这样做:

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

有关详细信息,请参阅此处


Tin*_*ank 12

我使用以下代码:

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);
}
Run Code Online (Sandbox Code Playgroud)

我认为在午夜运行函数有合法的用例.例如,就我而言,我在网站上显示了一些日常统计数据.如果网站恰好在午夜开放,则需要重置这些统计信息.

此外,还有这个答案.