Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define multiple jobs with same name programmatically in Node Agenda

I am using node Agenda module to fire up various jobs/events users created. I want to be able to create Jobs such that all of them are handled by one function call back, with each Event is distinguished based on the event parameters. Example code Below

var mongoConnectionString = "mongodb://127.0.0.1/agenda";
var Agenda = require('agenda');
var agenda = new Agenda({db: {address: mongoConnectionString}});

agenda.define('user defined event', function(job,done) {
    var eventParams = job.attrs.data;
    if(eventParams.params === "Test"){
        handleEvent1();
    } else if (eventParams.params === "Test 2") {
        handleEvent2();
    } else {
        handleEvent3();
    }

    done();
});

agenda.on('ready', function() {
  console.log("Ok Lets get start");
  agenda.start();
});

// some how we get our call back executed. Note that params is the unique to each job.
var userEvent = function(params) {
    // Handle a event which repeats every 10 secs
    agenda.every('10 seconds','user defined event',params);
}

With this code, Jobs in mongodb is updated instead of inserted. is there any way i can force the agenda to insert instead of update? if it is not possible with agenda, is there any other module which does this?

Thanks in advance for your valuable time

like image 569
rcreddy Avatar asked Mar 20 '17 10:03

rcreddy


1 Answers

It's because:

Every creates a job of type single, which means that it will only create one job in the database, even if that line is run multiple times.

You need to use agenda.create, job.repeatEvery and job.save to create multiple jobs with the same name:

const job = agenda.create("user defined event", params);
job.repeatEvery("10 seconds");
job.save();
like image 54
Lukasz Wiktor Avatar answered Nov 02 '22 04:11

Lukasz Wiktor