在节点计划中启动时运行任务?

问题描述

当使用 https://github.com/node-schedule/node-schedule 时,我想在定义后定期运行作业,但它确实会在一段时间后启动。 目前,我将其定义为:

void myFunction();
scheduleJob({ rule: "*/5 * * * *" },() => {
  void myFunction();
});

有没有更好的方法来做到这一点?

解决方法

Node schedule 没有此功能来在计划作业的初始化时调用函数。

一种方法,就是按照你定义的方式去做。

另一种方法是使用 cron npm 包。

const cronJob = require('cron').CronJob;

const myJob = new cronJob('"*/5 * * * *"',() => {
    myFunction();
 },() => {
 },true
); 

此处,true 标志指示模块实现在计划作业的初始化时运行该函数。