I want to schedule a simple task using Agenda with nodejs, however it is not executing when it is wrapped in apiRoutes (express router)
var apiRoutes = express.Router();
app.use('/api', apiRoutes);
apiRoutes.post('/scheduler/submit', function (req, res) {
agenda.define('test', function () {
console.log('Test');
});
agenda.on('ready', function () {
agenda.every('*/1 * * * *', 'test');
agenda.start();
});
});
but if i place that code outside, it works however. Hmm, any idea?
var apiRoutes = express.Router();
app.use('/api', apiRoutes);
agenda.define('test', function () {
console.log('Test');
});
agenda.on('ready', function () {
agenda.every('*/1 * * * *', 'test');
agenda.start();
});
apiRoutes.post('/scheduler/submit', function (req, res) {
// Leave blank
});
The problem is the
onfunction. When you call theagenda.on('ready', ...)in your express code you are adding a listen to theagendaemitter'sreadyarray but that signal only occurs whenagendaconnects to your database when the server initializes. In other words, afteragendaconnects to your database when the server starts up it will not emit that same signal again which is why the code in your express API isn't executing.To fix this, I'd recommend you confirm that
agendahas connected to your database successfully and run the process. If not, then add the.on('ready', ...)event listener.Sample source: