Search code examples
node.jsmongodbagenda

Preventing Immediate Execution When Saving Job to Agenda in Node


I am using agenda.js with Node, backed by MongoDB, to handle batch jobs. One issue I'm running into with the current syntax I'm using, is scheduling a repeating event, but not having it execute immediately. I am aware of the "skipImmediate: true" flag, but I'm not clear on where I need to apply that in my current configuration, where I use an IIFE:

  agenda.define('test job', {
    priority: 'high',
    concurrency: 10
  }, async job => {
    const {
      to
    } = job.attrs.data;
    job.repeatEvery('0 11 * * 1-5', {
      skipImmediate: true
    });
    await send(to);
  });

  function send(to) {
    const today = new Date();
    const target = to;
    const time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
    console.log(`Emailing to ${target} regarding second job, at ${time}.`);
  }

  (async function () {
    await agenda.start();
    agenda.create('test job', {
      to: '[email protected]',
      from: '[email protected]'
    }).save();
  })();
};

As you can see, I have...

{ skipImmediate: true }

... in the repeatEvery block, but it doesn't seem to work. How can I prevent immediate execution with my current configuration?


Solution

  • I think you are complicating the task, This might work in your case

    agenda.define('test job', {
        priority: 'high',
        concurrency: 10
    }, async job => {
        const {
            to
        } = job.attrs.data;
        const today = new Date();
        const target = to;
        const time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
        console.log(`Emailing to ${target} regarding second job, at ${time}.`);
    });
    

    This is for calling

    ;(async function() {
        const returned = agenda.create('test job', {
            to: '[email protected]',
            from: '[email protected]'
        })
        await agenda.start();
        await returned.repeatEvery('0 11 * * 1-5', {
            skipImmediate: true
        }).save()
    })();
    

    What this does is define will define what your agenda should do, then you create the agenda with parameters and start it. It returns the Job and you can repeat it using repeatEvery