6

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

rcreddy
  • 95
  • 7
  • 2
    it seems var job = agenda.create('user defined event', {to: 'another-guy@example.com', params: "Test 1"}) job.repeatEvery('10 seconds').save(); Seems to be doing the trick – rcreddy Mar 20 '17 at 10:37

1 Answers1

4

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();
Lukasz Wiktor
  • 19,644
  • 5
  • 69
  • 82
  • is there a definition of available Job.types? From what i can find in code there are "once", "single" and "normal". However i can not find what the normal type for job will do different from "single" – Laurynas Mališauskas Sep 22 '20 at 12:44
  • Sorry, I've no idea. ‍♂️ I also tried analyzing the source code, but couldn't figure it out. – Lukasz Wiktor Sep 22 '20 at 19:05
  • 1
    as my tests showed, "normal" type of job lets you run the same title job on several different time patterns. If the job is marked as "single" it only runs the first one. Hope this helps anyone who is struggling. – Laurynas Mališauskas Sep 24 '20 at 07:24