我想使用Node JS以特定的时间间隔执行三个函数。我已阅读了这篇文章I need a Nodejs scheduler that allows for tasks at different intervals
我尝试过使用node-cron
和node-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'))
我希望monthlySnapshot
以5 seconds
间隔运行,而dailySnapshot
将以10 seconds
间隔运行,changeFile
将在4 seconds
运行间隔。
现在monthlySnapshot
和dailySnapshot
访问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-cron
或node-schedule
的任何示例都可以。
当我单独使用nodemon notification.js
并正确发送电子邮件时,数据库访问工作正常。没有问题。
答案 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秒运行一次