nodejs定时任务node-schedule:

·不停止服务
·可在线开启关闭定时
·自定义定时名称
·在线查询当前正常执行的定时任务

1.schedule.js

const schedule = require('node-schedule');
const moment = require('moment');


/**
 * name定时名称
 * cron表达式
 * */
function startTimer(name, cron) {
    schedule.scheduleJob(name, cron, () => {
        console.error(name + "|....." + moment(new Date()).format("YYYY-MM-DD HH:mm:ss"))
    });
}

//每60秒执行一次名称为【22】的定时任务,整点执行
startTimer("22", "*/60 * * * * ?");
startTimer("33", "*/60 * * * * ?");
//开启一个错误定时,后做验证使用
startTimer("44", "*/60 * KKKKKK* * * ?");


//获取所有定时任务
for (let i in schedule.scheduledJobs) {
    console.error("任务名称:"+i);
}

//判断名为【22】的定时任务是否正常开启【nextInvocation()方法是指下一次任务执行的时间】
let nextInvocation = schedule.scheduledJobs['22'].nextInvocation();
console.error("TRUE - value:"+nextInvocation);
let nextInvocation2 = schedule.scheduledJobs['44'].nextInvocation();
console.error("FALSE - value:"+nextInvocation2);

//由上测试可知,当cron表达式错误时,定时未正常开启,此时应该关闭错误定时
schedule.scheduledJobs['44'].cancel();

//重新查看正确开启的定时任务
for (let i in schedule.scheduledJobs) {
    console.error("正确开启的定时任务名称:"+i);
}

2.测试结果:

任务名称:22
任务名称:33
任务名称:44
TRUE - value:Wed Nov 06 2019 11:45:00 GMT+0800
FALSE - value:null
正确开启的定时任务名称:22
正确开启的定时任务名称:33

更多推荐

【nodejs】定时任务node-schedule,不停止服务器,可在线开启关闭定时,自定义定时名称