I'm trying to add in Agenda into my node application so I can run some background tasks on a daily basis, e.g. Deactivating users who have not logged in for 60 days.
I've tried following the example on the GitHub associated with the module, but seem to be running into a problem with my app hanging whenever I try to load the site, and ultimately getting an "Error 504: Gateway Server Timeout". I'm also seeing undefined
in the console.
I know Agenda is up and working correctly, as I have a simple job at the moment that just does a console.log every minute.
In my app.js I require my worker.js file:
var agenda = require('./worker.js');
My worker.js is just a simple 1 line:
require('./lib/agenda.js');
agenda.js:
var Agenda = require('agenda');
var connectionString = "mongodb://" + process.env.MONGODB_USER + ":" +
process.env.MONGODB_PASSWORD + "@" +
process.env.DATABASE_SERVICE_NAME + ':' +
process.env.MONGODB_PORT + '/' +
process.env.MONGODB_DATABASE;
var agenda = new Agenda({db: {address: connectionString}});
var jobTypes = process.env.JOB_TYPES ? process.env.JOB_TYPES.split(',') : [];
jobTypes.forEach(function(type){
require('./jobs/' + type)(agenda);
});
if (jobTypes.length) {
agenda.on('ready', function() {
agenda.every('* * * * *', 'test job') //Run job at 0030 every day
agenda.start();
})
}
module.exports = agenda
and the test job is defined in a job file like so:
agenda.define('test job', function(job, done) {
console.log ('Agenda job executed');
done();
});
I feel like I am missing something really obvious!
It turns out that I needed to add an agenda.processEvery
in the start command section of my agenda.js:
var Agenda = require('agenda');
var connectionString = "mongodb://" + process.env.MONGODB_USER + ":" +
process.env.MONGODB_PASSWORD + "@" +
process.env.DATABASE_SERVICE_NAME + ':' +
process.env.MONGODB_PORT + '/' +
process.env.MONGODB_DATABASE;
var agenda = new Agenda({db: {address: connectionString}});
var jobTypes = process.env.JOB_TYPES ? process.env.JOB_TYPES.split(',') : [];
jobTypes.forEach(function(type){
require('./jobs/' + type)(agenda);
});
if (jobTypes.length) {
agenda.on('ready', function() {
agenda.every('* * * * *', 'test job') //Run job at 0030 every day
agenda.processEvery('one minute'); //<====== This is the new line
agenda.start();
})
}
module.exports = agenda