1

I want to generate tasks defined by users. Basically they have some inputs ex: dropdown with weekDays when they want the cron to run, startDate and timezone. This tasks are defined for projects. On the project they define when they want to create some reports.

That how my code looks now

/src/agenda.js

    const Agenda = require('agenda');
    
    const connectionOpts = {db: {address: process.env.MONGODB_URI'}};
    
    const agenda = new Agenda(connectionOpts);
    
    const jobTypes = ["create-report"];
    
    jobTypes.forEach(type => {
      require('./jobs/' + type);
    });
    
    if (jobTypes.length) {
      agenda.start(); // Returns a promise, which should be handled appropriately
    }
    
    module.exports = agenda;

/src/jobs/create-report.js

     agenda.define("create-report", (job: any, done: any) => {
          console.log('hello');
        })

/src/controllers/project.controller

// ProjectController, after project update process data
await agenda.schedule('in 10 seconds', 'create-report', {to: 'xyz@example.com', project: project});

I saw that job is created in database but it's not running the job. I'm using LoopBack as framework.

Rohit Ambre
  • 921
  • 1
  • 11
  • 25
paratif
  • 11
  • 1

1 Answers1

1

move your /src/agenda.js file into boot folder of loopback so it will automatically get triggered every time server starts.

and change agenda start code like this.

if (jobTypes.length) {
    // if there are jobs in the jobsTypes array set up
    agenda.on('ready',  () => {
      console.log('ready');
      agenda.start();
    });
  }
Rohit Ambre
  • 921
  • 1
  • 11
  • 25
  • Hello @Rohit I did this. The problem si how can I access now "agenda" in other controllers? to do schedules – paratif Jul 30 '20 at 10:01
  • Are you not able to access `agenda` inside controller by importing that file? – Rohit Ambre Jul 30 '20 at 10:06
  • Basically I created an observer I don't know how to import from observer. I'm using loopback4 and I can't see a boot folder – paratif Jul 30 '20 at 10:12
  • `boot` folder is thing with the loopback 3, I haven't checked loopback 4, but they will surely have something same going there as well – Rohit Ambre Jul 30 '20 at 12:30
  • i tried to put the content of the src/agenda.js into an observer, I was able to run the agenda...but the observer is using start() and from start() I can't access methods like agenda.schedule – paratif Jul 30 '20 at 14:05
  • I'll have to look into loopback4, and then i'll comeback to it. – Rohit Ambre Jul 30 '20 at 14:22