Task defined by users with AgendaJS

110 Views Asked by At

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: '[email protected]', project: project});

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

1

There are 1 best solutions below

6
On

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();
    });
  }