【问题标题】:How to fire onComplete function while using node-cron?使用 node-cron 时如何触发 onComplete 功能?
【发布时间】:2016-11-14 03:47:30
【问题描述】:

我正在使用node-cron 在作业运行时触发函数 (onTick),并在作业停止时触发函数 (onComplete);但是,我没有得到预期的行为。

如果作业实际运行,则 onComplete 永远不会运行:

var CronJob = require('cron').CronJob;
var someDate = new Date('July 11, 2016 20:44:20');
var timeZone = 'America/Los_Angeles'

var job = new CronJob(someDate, function() {
        /* runs once at the specified date. */
        console.log("job running")
    }, function() {
        /* This function is executed when the job stops */
        console.log("job stopping")
    },
    true, /* Start the job right now */
    timeZone /* Time zone of this job. */
);

输出:

hello-node-cron ❯ node date-usage.js
job running

但奇怪的是,如果日期已经过去,那么onComplete 将运行:

输出:

hello-node-cron ❯ node date-usage.js
job stopping

我错过了什么吗?

【问题讨论】:

    标签: javascript node.js npm cron


    【解决方案1】:

    撇开直觉不谈,根据 one 的测试用例,onComplete 是通过设计调用 stop API 来触发的。

    var job = new CronJob(someDate, function() {
            /* runs once at the specified date. */
            console.log("job running")
            this.stop() // <===================================== Add stop here.
        }, function() {
            /* This function is executed when the job stops */
            console.log("job stopping")
        },
        true, /* Start the job right now */
        timeZone /* Time zone of this job. */
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-29
      • 1970-01-01
      • 2019-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-02
      相关资源
      最近更新 更多