chandradot99
chandradot99

Reputation: 3866

How to run task in every 5 seconds with agenda in nodejs

I am using agenda to run jobs in my nodejs application, below is my agenda.js file for agenda config.

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;

Below is my script to run a game play in every 5 seconds,

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();
  });

}

After running my agenda.js script, below is my job which gets saved in the database,

{ "_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") }

Instead of 5 seconds,my job is running after every 5 minutes, what can be the problem.

Upvotes: 3

Views: 8507

Answers (2)

helloworld
helloworld

Reputation: 161

add done() to finish the process. Hope it help!

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

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

}

Upvotes: 3

Tuko90
Tuko90

Reputation: 59

Agenda module is based on human interval module(https://github.com/rschmukler/human-interval).

On the documentation you can see that seconds are supported but the min interval you can set is 1 minute.

They say that seconds are supported because you can set the interval as '1 minute and 30 seconds'.

You can try to pass interval as cron format:

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();
  });

}

It it's not supported you would need to consider to use a different module like https://www.npmjs.com/package/node-cron or https://www.npmjs.com/package/node-schedule

Upvotes: 0

Related Questions