1

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
Dev
  • 413
  • 10
  • 27

1 Answers1

1

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

eol
  • 23,236
  • 5
  • 46
  • 64
  • Thanks for help but if I do agenda.on('ready', startJob(agenda) ) I'm still passing agenda object here but why it's not working ? – Dev Apr 18 '19 at 08:38
  • 1
    Because an event handler requires a callback-function, you cannot pass an already called function -> check out https://nodejs.org/api/events.html#events_emitter_on_eventname_listener – eol Apr 18 '19 at 08:53
  • Now If I write above code module.exports = function(agenda) { agenda.define('test', function(job, done) { }); agenda.on('ready', startJob(agenda)); function startJob(agenda) { agenda.every('*/5 * * * * *', 'test'); agenda.start(); } } I just defined startJob inside module.exports function, it's working, how you will explain it? – Dev Apr 18 '19 at 09:06