我想使用 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 秒
间隔运行,而 dailySnapshot
以 10 秒
间隔运行changeFile
将以 4 秒
间隔运行。
现在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
并正确发送电子邮件时,数据库访问工作正常。那里没有问题。
最佳答案
我使用 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 秒运行一次
关于mysql - 在 Node JS 中安排多个函数以特定时间间隔运行(CRON JOB),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44546902/