安排多个函数在Node JS中以特定间隔运行(CRON JOB)

时间:2017-06-14 13:56:30

标签: mysql node.js cron

我想使用Node JS以特定的时间间隔执行三个函数。我已阅读了这篇文章I need a Nodejs scheduler that allows for tasks at different intervals

我尝试过使用node-cronnode-schedule。但它没有用!!

我的代码如下,

var schedule = require('node-schedule')


var fs = require('fs')
var tar = require('tar')

var notification = require('./notification')

let changeInDir = function () {
    console.log('Testing CRON JOB !!!', new Date().toLocaleString())
    fs.watch('./test', (event, filename) => {
        console.log('a', event, 'event occurred.. on file', filename)
    })
}

// schedule a CRON Job
var changeFile = schedule.scheduleJob('4 * * * * *', changeInDir);


// send the Monthly snapshots
var monthlySnapshot = schedule.scheduleJob('5 * * * * *', notification.getViewDetails('Monthly'))

// send the Daily snapshots
var dailySnapshot= schedule.scheduleJob('10 * * * * *', notification.getViewDetails('Daily'))

我希望monthlySnapshot5 seconds间隔运行,而dailySnapshot将以10 seconds间隔运行,changeFile将在4 seconds运行间隔。

现在monthlySnapshotdailySnapshot访问MySQL数据库以获取数据并相应地发送电子邮件。如果我只安排changeFile并对其他人发表评论,那就可以了。但是当我尝试执行所有这三个时,它会给出以下错误消息并崩溃。

C:\Users\asau\Documents\LeaderBoardNodejs\archlb\src\server\node_modules\node-schedule\lib\schedule.js:174
    this.job.execute();
             ^

TypeError: this.job.execute is not a function
    at Job.invoke (C:\Users\asau\Documents\LeaderBoardNodejs\archlb\src\server\node_modules\node-schedule\lib\schedule.js:174:14)
    at Timeout._onTimeout (C:\Users\asau\Documents\LeaderBoardNodejs\archlb\src\server\node_modules\node-schedule\lib\schedule.js:542:11)
    at ontimeout (timers.js:365:14)
    at tryOnTimeout (timers.js:237:5)
    at Timer.listOnTimeout (timers.js:207:5)
[nodemon] app crashed - waiting for file changes before starting...

如何解决?使用node-cronnode-schedule的任何示例都可以。

当我单独使用nodemon notification.js并正确发送电子邮件时,数据库访问工作正常。没有问题。

1 个答案:

答案 0 :(得分:0)

我使用node cron https://www.npmjs.com/package/cron

var momentTz = require('moment-timezone');
var CronJob = require('cron').CronJob;
var job = new CronJob('*/4 * * * * *', function() {
var a = momentTz.tz("Europe/Helsinki");
 //your logic
}, function () {

   console.log('work ended');
},
true,
'Europe/Helsinki'
);

job.start();

它每4秒运行一次