Search code examples
node.jsmongodbagenda

Scheduling Repeating Daily Jobs with Agenda.js and Node


I am setting up a job scheduler using Agenda.js and Node, backed with MongoDB. So far it's working as expected. However, I'm unclear how to schedule a repeating job -- for instance, a job that should run every day at 9am.

"schedule" is used for a one-time scheduling of a job, but not repeats:

agenda.schedule('today at 09:00am CST', 'first job');

"every" works with an interval like "3 minutes", but not with "day at 9:00am"

agenda.every('3 minutes', 'second job');

Since configuration methods are supposedly chainable I also tried this:

agenda.processEvery('24 hours').schedule('day at 09:45am CST', 'second job');

... this did run the task successfully the first time 9:45am CST arrived, but it didn't reset it to run the next day at the same time.

What syntax would I use to run a job EVERY day at 9:00am? And, even better, how can I schedule that to run on Monday - Friday only?


Solution

  • Ajenda accepts cron format. So you can do something like this

    This is repeat Job At 09:00 on every day-of-week from Monday through Friday

    job.repeatEvery('0 9 * * 1-5', {
        skipImmediate: true
    });
    

    SkipImmediate is Optional. Here is CRON checker for above cron string. Read more about repeatEvery

    EDIT

    Job is returned when Agenda is made

    agenda.define('NAME', async job => {
                job.repeatEvery('0 9 * * 1-5', {
                    skipImmediate: true
                });
                await job.save()
            }
    

    Read more about Creating Jobs