如何在nodejs中每隔5秒运行一次任务

问题描述:

我正在使用议程在我的nodejs应用程序中运行作业,以下是我的agenda.js文件的议程配置。如何在nodejs中每隔5秒运行一次任务

var Agenda = require('agenda'); 

var connectionString = 'localhost:27017/csgo'; 
var agenda = new Agenda({db: { address: connectionString, collection: 'jobs' }}); 

require('./jobs/game_play')(agenda); 

module.exports = agenda; 

下面是我的脚本运行每5秒一个的游戏,

module.exports = function(agenda) { 
    agenda.define('start new play', function(job, done) { 
    console.log('new play agenda'); 
    }); 

    agenda.on('ready', function() { 
    agenda.every('5 seconds', 'start new play'); 
    agenda.start(); 
    }); 

} 

运行我agenda.js脚本之后,下面是我的工作,这被保存在数据库中,

{ "_id" : ObjectId("59423d0e4b9581f728af1b6a"), "name" : "start new play", "type" : "single", "data" : null, "priority" : 0, "repeatInterval" : "5 seconds", "repeatTimezone" : null, "lastModifiedBy" : null, "nextRunAt" : ISODate("2017-06-15T07:53:55.794Z"), "lockedAt" : ISODate("2017-06-15T07:53:50.789Z"), "lastRunAt" : ISODate("2017-06-15T07:53:50.794Z") } 

而不是5 seconds,我的工作是在每5 minutes之后运行,可能是什么问题。

+0

您是否尝试过使用'processEvery() '?看看这里https://github.com/rschmukler/agenda,我认为你应该去'processEvery()'而不是'every()' – Abrar

议程模块基于人类间隔模块(https://github.com/rschmukler/human-interval)。

在文档上可以看到支持秒,但可以设置的最小时间间隔为1分钟。

他们说秒支持,因为你可以设置间隔为'1分30秒'。

您可以尝试遍间隔为的cron格式:

module.exports = function(agenda) { 
    agenda.define('start new play', function(job, done) { 
    console.log('new play agenda'); 
    }); 

    agenda.on('ready', function() { 
    agenda.every('*/5 * * * * *', 'start new play'); 
    agenda.start(); 
    }); 

} 

它它不支持,你需要考虑使用不同的模块,像https://www.npmjs.com/package/node-cronhttps://www.npmjs.com/package/node-schedule