Search code examples
node.jsmongooseagenda

Convert NodeJS agenda ready event anonymous function to normal function


I'm using NodeJS Agenda module for job scheduling. In agenda there is an event 'ready'

module.exports = function(agenda) {
 agenda.define('test', function(job, done) {

});

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

}

Here inside on ready event I'm using an anonymous function, but I don't want to use anonymous function, want to create a normal function.

for example

module.exports = function(agenda) {
 agenda.define('test', function(job, done) {

});

 agenda.on('ready', startJob());

}


function startJob(agenda) {
 agenda.every('*/5 * * * * *', 'test');
 agenda.start();
}

but it's not working getting

Cannot read property 'start' of undefined

Solution

  • The problem is that you're directly invoking the function without passing the agenda-object. One way to solve this, would be:

    agenda.on('ready', () => { startJob(agenda); });

    Or if you want to pass the startJob-function as the callback, you'd need to bind the agenda-object to it:

    agenda.on('ready', startJob.bind(this, agenda));