Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

@hokify/agenda

hokify80.8kMIT6.3.0TypeScript support: included

Light weight job scheduler for Node.js

job, jobs, cron, delayed, scheduler, runner

readme

AgendaTS

(full typed version of agendaJS)

Agenda TS

A light-weight job scheduling library for Node.js

This was originally a fork of agenda.js, it differs from the original version in following points:

  • Complete rewrite in Typescript (fully typed!)
  • mongodb4 driver (supports mongodb 5.x)
  • Supports mongoDB sharding by name
  • touch() can have an optional progress parameter (0-100)
  • Bugfixes and improvements for locking & job processing (concurrency, lockLimit,..)
  • Breaking change: define() config paramter moved from 2nd position to 3rd
  • getRunningStats()
  • automatically waits for agenda to be connected before calling any database operations
  • uses a database abstraction layer behind the scene
  • does not create a database index by default, you can set ensureIndex: true when initializing Agenda or run manually:
db.agendaJobs.ensureIndex({
    "name" : 1,
    "nextRunAt" : 1,
    "priority" : -1,
    "lockedAt" : 1,
    "disabled" : 1
}, "findAndLockNextJobIndex")

Agenda offers

  • Minimal overhead. Agenda aims to keep its code base small.
  • Mongo backed persistence layer.
  • Promises based API.
  • Scheduling with configurable priority, concurrency, and repeating.
  • Scheduling via cron or human readable syntax.
  • Event backed job queue that you can hook into.
  • Agendash: optional standalone web-interface.
  • Agenda-rest: optional standalone REST API.
  • inversify-agenda - Some utilities for the development of agenda workers with Inversify

Feature Comparison

Since there are a few job queue solutions, here a table comparing them to help you use the one that better suits your needs.

Feature Bull Bee Agenda AgendaTS
Backend redis redis mongo mongo
Priorities | ✓
Concurrency
Delayed jobs | ✓
Global events |
Rate Limiter |
Pause/Resume |
Sandboxed worker |
Repeatable jobs | ✓
Atomic ops | ~
Persistence
UI | ✓
REST API |
Central (Scalable) Queue | | ✓
Supports long running jobs | | ✓
Optimized for Jobs / Messages Messages Jobs Jobs

Kudos for making the comparison chart goes to Bull maintainers.

Installation

Install via NPM

npm install @hokify/agenda

You will also need a working Mongo database (v4+) to point it to.

Example Usage

const mongoConnectionString = 'mongodb://127.0.0.1/agenda';

const agenda = new Agenda({ db: { address: mongoConnectionString } });

// Or override the default collection name:
// const agenda = new Agenda({db: {address: mongoConnectionString, collection: 'jobCollectionName'}});

// or pass additional connection options:
// const agenda = new Agenda({db: {address: mongoConnectionString, collection: 'jobCollectionName', options: {ssl: true}}});

// or pass in an existing mongodb-native MongoClient instance
// const agenda = new Agenda({mongo: myMongoClient});

agenda.define('delete old users', async job => {
    await User.remove({ lastLogIn: { $lt: twoDaysAgo } });
});

(async function () {
    // IIFE to give access to async/await
    await agenda.start();

    await agenda.every('3 minutes', 'delete old users');

    // Alternatively, you could also do:
    await agenda.every('*/3 * * * *', 'delete old users');
})();
agenda.define(
    'send email report',
    async job => {
        const { to } = job.attrs.data;
        await emailClient.send({
            to,
            from: 'example@example.com',
            subject: 'Email Report',
            body: '...'
        });
    },
    { priority: 'high', concurrency: 10 }
);

(async function () {
    await agenda.start();
    await agenda.schedule('in 20 minutes', 'send email report', { to: 'admin@example.com' });
})();
(async function () {
    const weeklyReport = agenda.create('send email report', { to: 'example@example.com' });
    await agenda.start();
    await weeklyReport.repeatEvery('1 week').save();
})();

Full documentation

See also https://hokify.github.io/agenda/

Agenda's basic control structure is an instance of an agenda. Agenda's are mapped to a database collection and load the jobs from within.

Table of Contents

Configuring an agenda

All configuration methods are chainable, meaning you can do something like:

const agenda = new Agenda();
agenda
  .database(...)
  .processEvery('3 minutes')
  ...;

Possible agenda config options:

{
    name: string;
    defaultConcurrency: number;
    processEvery: number;
    maxConcurrency: number;
    defaultLockLimit: number;
    lockLimit: number;
    defaultLockLifetime: number;
    ensureIndex: boolean;
    sort: SortOptionObject<IJobParameters>;
    db: {
        collection: string;
        address: string;
        options: MongoClientOptions;
    };
    mongo: Db;
}

Agenda uses Human Interval for specifying the intervals. It supports the following units:

seconds, minutes, hours, days,weeks, months -- assumes 30 days, years -- assumes 365 days

More sophisticated examples

agenda.processEvery('one minute');
agenda.processEvery('1.5 minutes');
agenda.processEvery('3 days and 4 hours');
agenda.processEvery('3 days, 4 hours and 36 seconds');

database(url, [collectionName], [MongoClientOptions])

Specifies the database at the url specified. If no collection name is given, agendaJobs is used.

By default useNewUrlParser and useUnifiedTopology is set to true,

agenda.database('localhost:27017/agenda-test', 'agendaJobs');

You can also specify it during instantiation.

const agenda = new Agenda({
    db: { address: 'localhost:27017/agenda-test', collection: 'agendaJobs' }
});

Agenda will emit a ready event (see Agenda Events) when properly connected to the database. It is safe to call agenda.start() without waiting for this event, as this is handled internally. If you're using the db options, or call database, then you may still need to listen for ready before saving jobs.

mongo(dbInstance, [collectionName])

Use an existing mongodb-native MongoClient/Db instance. This can help consolidate connections to a database. You can instead use .database to have agenda handle connecting for you.

You can also specify it during instantiation:

const agenda = new Agenda({ mongo: mongoClientInstance.db('agenda-test') });

Note that MongoClient.connect() returns a mongoClientInstance since node-mongodb-native 3.0.0, while it used to return a dbInstance that could then be directly passed to agenda.

name(name)

Takes a string name and sets lastModifiedBy to it in the job database. Useful for if you have multiple job processors (agendas) and want to see which job queue last ran the job.

agenda.name(os.hostname + '-' + process.pid);

You can also specify it during instantiation

const agenda = new Agenda({ name: 'test queue' });

processEvery(interval)

Takes a string interval which can be either a traditional javascript number, or a string such as 3 minutes

Specifies the frequency at which agenda will query the database looking for jobs that need to be processed. Agenda internally uses setTimeout to guarantee that jobs run at (close to ~3ms) the right time.

Decreasing the frequency will result in fewer database queries, but more jobs being stored in memory.

Also worth noting is that if the job queue is shutdown, any jobs stored in memory that haven't run will still be locked, meaning that you may have to wait for the lock to expire. By default it is '5 seconds'.

agenda.processEvery('1 minute');

You can also specify it during instantiation

const agenda = new Agenda({ processEvery: '30 seconds' });

maxConcurrency(number)

Takes a number which specifies the max number of jobs that can be running at any given moment. By default it is 20.

agenda.maxConcurrency(20);

You can also specify it during instantiation

const agenda = new Agenda({ maxConcurrency: 20 });

defaultConcurrency(number)

Takes a number which specifies the default number of a specific job that can be running at any given moment. By default it is 5.

agenda.defaultConcurrency(5);

You can also specify it during instantiation

const agenda = new Agenda({ defaultConcurrency: 5 });

lockLimit(number)

Takes a number which specifies the max number jobs that can be locked at any given moment. By default it is 0 for no max.

agenda.lockLimit(0);

You can also specify it during instantiation

const agenda = new Agenda({ lockLimit: 0 });

defaultLockLimit(number)

Takes a number which specifies the default number of a specific job that can be locked at any given moment. By default it is 0 for no max.

agenda.defaultLockLimit(0);

You can also specify it during instantiation

const agenda = new Agenda({ defaultLockLimit: 0 });

defaultLockLifetime(number)

Takes a number which specifies the default lock lifetime in milliseconds. By default it is 10 minutes. This can be overridden by specifying the lockLifetime option to a defined job.

A job will unlock if it is finished (ie. the returned Promise resolves/rejects or done is specified in the params and done() is called) before the lockLifetime. The lock is useful if the job crashes or times out.

agenda.defaultLockLifetime(10000);

You can also specify it during instantiation

const agenda = new Agenda({ defaultLockLifetime: 10000 });

sort(query)

Takes a query which specifies the sort query to be used for finding and locking the next job.

By default it is { nextRunAt: 1, priority: -1 }, which obeys a first in first out approach, with respect to priority.

Agenda Events

An instance of an agenda will emit the following events:

  • ready - called when Agenda mongo connection is successfully opened and indices created. If you're passing agenda an existing connection, you shouldn't need to listen for this, as agenda.start() will not resolve until indices have been created. If you're using the db options, or call database, then you may still need to listen for the ready event before saving jobs. agenda.start() will still wait for the connection to be opened.
  • error - called when Agenda mongo connection process has thrown an error
await agenda.start();

Defining Job Processors

Before you can use a job, you must define its processing behavior.

define(jobName, fn, [options])

Defines a job with the name of jobName. When a job of jobName gets run, it will be passed to fn(job, done). To maintain asynchronous behavior, you may either provide a Promise-returning function in fn or provide done as a second parameter to fn. If done is specified in the function signature, you must call done() when you are processing the job. If your function is synchronous or returns a Promise, you may omit done from the signature.

options is an optional argument which can overwrite the defaults. It can take the following:

  • concurrency: number maximum number of that job that can be running at once (per instance of agenda)
  • lockLimit: number maximum number of that job that can be locked at once (per instance of agenda)
  • lockLifetime: number interval in ms of how long the job stays locked for (see multiple job processors for more info). A job will automatically unlock once a returned promise resolves/rejects (or if done is specified in the signature and done() is called).
  • priority: (lowest|low|normal|high|highest|number) specifies the priority of the job. Higher priority jobs will run first. See the priority mapping below

Priority mapping:

{
  highest: 20,
  high: 10,
  normal: 0,
  low: -10,
  lowest: -20
}

Async Job:

agenda.define('some long running job', async job => {
    const data = await doSomelengthyTask();
    await formatThatData(data);
    await sendThatData(data);
});

Async Job (using done):

agenda.define('some long running job', (job, done) => {
    doSomelengthyTask(data => {
        formatThatData(data);
        sendThatData(data);
        done();
    });
});

Sync Job:

agenda.define('say hello', job => {
    console.log('Hello!');
});

define() acts like an assignment: if define(jobName, ...) is called multiple times (e.g. every time your script starts), the definition in the last call will overwrite the previous one. Thus, if you define the jobName only once in your code, it's safe for that call to execute multiple times.

Creating Jobs

every(interval, name, [data], [options])

Runs job name at the given interval. Optionally, data and options can be passed in. 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. This lets you put it in a file that may get run multiple times, such as webserver.js which may reboot from time to time.

interval can be a human-readable format String, a cron format String, or a Number.

data is an optional argument that will be passed to the processing function under job.attrs.data.

options is an optional argument that will be passed to job.repeatEvery. In order to use this argument, data must also be specified.

Returns the job.

agenda.define('printAnalyticsReport', async job => {
    const users = await User.doSomethingReallyIntensive();
    processUserData(users);
    console.log('I print a report!');
});

agenda.every('15 minutes', 'printAnalyticsReport');

Optionally, name could be array of job names, which is convenient for scheduling different jobs for same interval.

agenda.every('15 minutes', ['printAnalyticsReport', 'sendNotifications', 'updateUserRecords']);

In this case, every returns array of jobs.

schedule(when, name, [data])

Schedules a job to run name once at a given time. when can be a Date or a String such as tomorrow at 5pm.

data is an optional argument that will be passed to the processing function under job.attrs.data.

Returns the job.

agenda.schedule('tomorrow at noon', 'printAnalyticsReport', { userCount: 100 });

Optionally, name could be array of job names, similar to the every method.

agenda.schedule('tomorrow at noon', [
    'printAnalyticsReport',
    'sendNotifications',
    'updateUserRecords'
]);

In this case, schedule returns array of jobs.

now(name, [data])

Schedules a job to run name once immediately.

data is an optional argument that will be passed to the processing function under job.attrs.data.

Returns the job.

agenda.now('do the hokey pokey');

create(jobName, data)

Returns an instance of a jobName with data. This does NOT save the job in the database. See below to learn how to manually work with jobs.

const job = agenda.create('printAnalyticsReport', { userCount: 100 });
await job.save();
console.log('Job successfully saved');

Managing Jobs

jobs(mongodb-native query, mongodb-native sort, mongodb-native limit, mongodb-native skip)

Lets you query (then sort, limit and skip the result) all of the jobs in the agenda job's database. These are full mongodb-native find, sort, limit and skip commands. See mongodb-native's documentation for details.

const jobs = await agenda.jobs({ name: 'printAnalyticsReport' }, { data: -1 }, 3, 1);
// Work with jobs (see below)

cancel(mongodb-native query)

Cancels any jobs matching the passed mongodb-native query, and removes them from the database. Returns a Promise resolving to the number of cancelled jobs, or rejecting on error.

const numRemoved = await agenda.cancel({ name: 'printAnalyticsReport' });

This functionality can also be achieved by first retrieving all the jobs from the database using agenda.jobs(), looping through the resulting array and calling job.remove() on each. It is however preferable to use agenda.cancel() for this use case, as this ensures the operation is atomic.

purge()

Removes all jobs in the database without defined behaviors. Useful if you change a definition name and want to remove old jobs. Returns a Promise resolving to the number of removed jobs, or rejecting on error.

IMPORTANT: Do not run this before you finish defining all of your jobs. If you do, you will nuke your database of jobs.

const numRemoved = await agenda.purge();

Starting the job processor

To get agenda to start processing jobs from the database you must start it. This will schedule an interval (based on processEvery) to check for new jobs and run them. You can also stop the queue.

start

Starts the job queue processing, checking processEvery time to see if there are new jobs. Must be called after processEvery, and before any job scheduling (e.g. every).

stop

Stops the job queue processing. Unlocks currently running jobs.

This can be very useful for graceful shutdowns so that currently running/grabbed jobs are abandoned so that other job queues can grab them / they are unlocked should the job queue start again. Here is an example of how to do a graceful shutdown.

async function graceful() {
    await agenda.stop();
    process.exit(0);
}

process.on('SIGTERM', graceful);
process.on('SIGINT', graceful);

Multiple job processors

Sometimes you may want to have multiple node instances / machines process from the same queue. Agenda supports a locking mechanism to ensure that multiple queues don't process the same job.

You can configure the locking mechanism by specifying lockLifetime as an interval when defining the job.

agenda.define(
    'someJob',
    (job, cb) => {
        // Do something in 10 seconds or less...
    },
    { lockLifetime: 10000 }
);

This will ensure that no other job processor (this one included) attempts to run the job again for the next 10 seconds. If you have a particularly long running job, you will want to specify a longer lockLifetime.

By default it is 10 minutes. Typically you shouldn't have a job that runs for 10 minutes, so this is really insurance should the job queue crash before the job is unlocked.

When a job is finished (i.e. the returned promise resolves/rejects or done is specified in the signature and done() is called), it will automatically unlock.

Manually working with a job

A job instance has many instance methods. All mutating methods must be followed with a call to await job.save() in order to persist the changes to the database.

repeatEvery(interval, [options])

Specifies an interval on which the job should repeat. The job runs at the time of defining as well in configured intervals, that is "run now and in intervals".

interval can be a human-readable format String, a cron format String, or a Number.

options is an optional argument containing:

options.timezone: should be a string as accepted by moment-timezone and is considered when using an interval in the cron string format.

options.skipImmediate: true | false (default) Setting this true will skip the immediate run. The first run will occur only in configured interval.

job.repeatEvery('10 minutes');
await job.save();
job.repeatEvery('3 minutes', {
    skipImmediate: true
});
await job.save();
job.repeatEvery('0 6 * * *', {
    timezone: 'America/New_York'
});
await job.save();

repeatAt(time)

Specifies a time when the job should repeat. Possible values

job.repeatAt('3:30pm');
await job.save();

schedule(time)

Specifies the next time at which the job should run.

job.schedule('tomorrow at 6pm');
await job.save();

priority(priority)

Specifies the priority weighting of the job. Can be a number or a string from the above priority table.

job.priority('low');
await job.save();

unique(properties, [options])

Ensure that only one instance of this job exists with the specified properties

options is an optional argument which can overwrite the defaults. It can take the following:

  • insertOnly: boolean will prevent any properties from persisting if the job already exists. Defaults to false.
job.unique({ 'data.type': 'active', 'data.userId': '123', nextRunAt: date });
await job.save();

IMPORTANT: To avoid high CPU usage by MongoDB, make sure to create an index on the used fields, like data.type and data.userId for the example above.

fail(reason)

Sets job.attrs.failedAt to now, and sets job.attrs.failReason to reason.

Optionally, reason can be an error, in which case job.attrs.failReason will be set to error.message

job.fail('insufficient disk space');
// or
job.fail(new Error('insufficient disk space'));
await job.save();

run(callback)

Runs the given job and calls callback(err, job) upon completion. Normally you never need to call this manually.

job.run((err, job) => {
    console.log("I don't know why you would need to do this...");
});

save()

Saves the job.attrs into the database. Returns a Promise resolving to a Job instance, or rejecting on error.

try {
    await job.save();
    cosole.log('Successfully saved job to collection');
} catch (e) {
    console.error('Error saving job to collection');
}

remove()

Removes the job from the database. Returns a Promise resolving to the number of jobs removed, or rejecting on error.

try {
    await job.remove();
    console.log('Successfully removed job from collection');
} catch (e) {
    console.error('Error removing job from collection');
}

disable()

Disables the job. Upcoming runs won't execute.

enable()

Enables the job if it got disabled before. Upcoming runs will execute.

touch()

Resets the lock on the job. Useful to indicate that the job hasn't timed out when you have very long running jobs. The call returns a promise that resolves when the job's lock has been renewed.

agenda.define('super long job', async job => {
    await doSomeLongTask();
    await job.touch();
    await doAnotherLongTask();
    await job.touch();
    await finishOurLongTasks();
});

Job Queue Events

An instance of an agenda will emit the following events:

  • start - called just before a job starts
  • start:job name - called just before the specified job starts
agenda.on('start', job => {
    console.log('Job %s starting', job.attrs.name);
});
  • complete - called when a job finishes, regardless of if it succeeds or fails
  • complete:job name - called when a job finishes, regardless of if it succeeds or fails
agenda.on('complete', job => {
    console.log(`Job ${job.attrs.name} finished`);
});
  • success - called when a job finishes successfully
  • success:job name - called when a job finishes successfully
agenda.on('success:send email', job => {
    console.log(`Sent Email Successfully to ${job.attrs.data.to}`);
});
  • fail - called when a job throws an error
  • fail:job name - called when a job throws an error
agenda.on('fail:send email', (err, job) => {
    console.log(`Job failed with error: ${err.message}`);
});

Frequently Asked Questions

What is the order in which jobs run?

Jobs are run with priority in a first in first out order (so they will be run in the order they were scheduled AND with respect to highest priority).

For example, if we have two jobs named "send-email" queued (both with the same priority), and the first job is queued at 3:00 PM and second job is queued at 3:05 PM with the same priority value, then the first job will run first if we start to send "send-email" jobs at 3:10 PM. However if the first job has a priority of 5 and the second job has a priority of 10, then the second will run first (priority takes precedence) at 3:10 PM.

The default MongoDB sort object is { nextRunAt: 1, priority: -1 } and can be changed through the option sort when configuring Agenda.

What is the difference between lockLimit and maxConcurrency?

Agenda will lock jobs 1 by one, setting the lockedAt property in mongoDB, and creating an instance of the Job class which it caches into the _lockedJobs array. This defaults to having no limit, but can be managed using lockLimit. If all jobs will need to be run before agenda's next interval (set via agenda.processEvery), then agenda will attempt to lock all jobs.

Agenda will also pull jobs from _lockedJobs and into _runningJobs. These jobs are actively being worked on by user code, and this is limited by maxConcurrency (defaults to 20).

If you have multiple instances of agenda processing the same job definition with a fast repeat time you may find they get unevenly loaded. This is because they will compete to lock as many jobs as possible, even if they don't have enough concurrency to process them. This can be resolved by tweaking the maxConcurrency and lockLimit properties.

Sample Project Structure?

Agenda doesn't have a preferred project structure and leaves it to the user to choose how they would like to use it. That being said, you can check out the example project structure below.

Can I Donate?

Thanks! I'm flattered, but it's really not necessary. If you really want to, you can find my gittip here.

Web Interface?

Agenda itself does not have a web interface built in but we do offer stand-alone web interface Agendash:

Agendash interface

Mongo vs Redis

The decision to use Mongo instead of Redis is intentional. Redis is often used for non-essential data (such as sessions) and without configuration doesn't guarantee the same level of persistence as Mongo (should the server need to be restarted/crash).

Agenda decides to focus on persistence without requiring special configuration of Redis (thereby degrading the performance of the Redis server on non-critical data, such as sessions).

Ultimately if enough people want a Redis driver instead of Mongo, I will write one. (Please open an issue requesting it). For now, Agenda decided to focus on guaranteed persistence.

Spawning / forking processes

Ultimately Agenda can work from a single job queue across multiple machines, node processes, or forks. If you are interested in having more than one worker, Bars3s has written up a fantastic example of how one might do it:

const cluster = require('cluster');
const os = require('os');

const httpServer = require('./app/http-server');
const jobWorker = require('./app/job-worker');

const jobWorkers = [];
const webWorkers = [];

if (cluster.isMaster) {
    const cpuCount = os.cpus().length;
    // Create a worker for each CPU
    for (let i = 0; i < cpuCount; i += 1) {
        addJobWorker();
        addWebWorker();
    }

    cluster.on('exit', (worker, code, signal) => {
        if (jobWorkers.indexOf(worker.id) !== -1) {
            console.log(
                `job worker ${worker.process.pid} exited (signal: ${signal}). Trying to respawn...`
            );
            removeJobWorker(worker.id);
            addJobWorker();
        }

        if (webWorkers.indexOf(worker.id) !== -1) {
            console.log(
                `http worker ${worker.process.pid} exited (signal: ${signal}). Trying to respawn...`
            );
            removeWebWorker(worker.id);
            addWebWorker();
        }
    });
} else {
    if (process.env.web) {
        console.log(`start http server: ${cluster.worker.id}`);
        // Initialize the http server here
        httpServer.start();
    }

    if (process.env.job) {
        console.log(`start job server: ${cluster.worker.id}`);
        // Initialize the Agenda here
        jobWorker.start();
    }
}

function addWebWorker() {
    webWorkers.push(cluster.fork({ web: 1 }).id);
}

function addJobWorker() {
    jobWorkers.push(cluster.fork({ job: 1 }).id);
}

function removeWebWorker(id) {
    webWorkers.splice(webWorkers.indexOf(id), 1);
}

function removeJobWorker(id) {
    jobWorkers.splice(jobWorkers.indexOf(id), 1);
}

Recovering lost Mongo connections ("auto_reconnect")

Agenda is configured by default to automatically reconnect indefinitely, emitting an error event when no connection is available on each process tick, allowing you to restore the Mongo instance without having to restart the application.

However, if you are using an existing Mongo client you'll need to configure the reconnectTries and reconnectInterval connection settings manually, otherwise you'll find that Agenda will throw an error with the message "MongoDB connection is not recoverable, application restart required" if the connection cannot be recovered within 30 seconds.

Example Project Structure

Agenda will only process jobs that it has definitions for. This allows you to selectively choose which jobs a given agenda will process.

Consider the following project structure, which allows us to share models with the rest of our code base, and specify which jobs a worker processes, if any at all.

- server.js
- worker.js
lib/
  - agenda.js
  controllers/
    - user-controller.js
  jobs/
    - email.js
    - video-processing.js
    - image-processing.js
   models/
     - user-model.js
     - blog-post.model.js

Sample job processor (eg. jobs/email.js)

let email = require('some-email-lib'),
    User = require('../models/user-model.js');

module.exports = function (agenda) {
    agenda.define('registration email', async job => {
        const user = await User.get(job.attrs.data.userId);
        await email(user.email(), 'Thanks for registering', 'Thanks for registering ' + user.name());
    });

    agenda.define('reset password', async job => {
        // Etc
    });

    // More email related jobs
};

lib/agenda.js

const Agenda = require('agenda');

const connectionOpts = { db: { address: 'localhost:27017/agenda-test', collection: 'agendaJobs' } };

const agenda = new Agenda(connectionOpts);

const jobTypes = process.env.JOB_TYPES ? process.env.JOB_TYPES.split(',') : [];

jobTypes.forEach(type => {
    require('./jobs/' + type)(agenda);
});

if (jobTypes.length) {
    agenda.start(); // Returns a promise, which should be handled appropriately
}

module.exports = agenda;

lib/controllers/user-controller.js

let app = express(),
    User = require('../models/user-model'),
    agenda = require('../worker.js');

app.post('/users', (req, res, next) => {
    const user = new User(req.body);
    user.save(err => {
        if (err) {
            return next(err);
        }
        agenda.now('registration email', { userId: user.primary() });
        res.send(201, user.toJson());
    });
});

worker.js

require('./lib/agenda.js');

Now you can do the following in your project:

node server.js

Fire up an instance with no JOB_TYPES, giving you the ability to process jobs, but not wasting resources processing jobs.

JOB_TYPES=email node server.js

Allow your http server to process email jobs.

JOB_TYPES=email node worker.js

Fire up an instance that processes email jobs.

JOB_TYPES=video-processing,image-processing node worker.js

Fire up an instance that processes video-processing/image-processing jobs. Good for a heavy hitting server.

Debugging Issues

If you think you have encountered a bug, please feel free to report it here:

Submit Issue

Please provide us with as much details as possible such as:

  • Agenda version
  • Environment (OSX, Linux, Windows, etc)
  • Small description of what happened
  • Any relevant stack track
  • Agenda logs (see below)

To turn on logging, please set your DEBUG env variable like so:

  • OSX: DEBUG="agenda:*" ts-node src/index.ts
  • Linux: DEBUG="agenda:*" ts-node src/index.ts
  • Windows CMD: set DEBUG=agenda:*
  • Windows PowerShell: $env:DEBUG = "agenda:*"

While not necessary, attaching a text file with this debug information would be extremely useful in debugging certain issues and is encouraged.

Known Issues

"Multiple order-by items are not supported. Please specify a single order-by item."

When running Agenda on Azure cosmosDB, you might run into this issue caused by Agenda's sort query used for finding and locking the next job. To fix this, you can pass custom sort option: sort: { nextRunAt: 1 }

Performance

It is recommended to set this index if you use agendash:

db.agendaJobs.ensureIndex({
    "nextRunAt" : -1,
    "lastRunAt" : -1,
    "lastFinishedAt" : -1
}, "agendash2")

If you have one job definition with thousand of instances, you can add this index to improve internal sorting query for faster sortings

db.agendaJobs.ensureIndex({
    "name" : 1,
    "disabled" : 1,
    "lockedAt" : 1
}, "findAndLockDeadJobs")

Sandboxed Worker - use child processes

It's possible to start jobs in a child process, this helps for example for long running processes to seperate them from the main thread. For example if one process consumes too much memory and gets killed, it will not affect any others. To use this feature, several steps are required. 1.) create a childWorker helper. The subrocess has a complete seperate context, so there are no database connections or anything else that can be shared. Therefore you have to ensure that all required connections and initializations are done here too. Furthermore you also have to load the correct job definition so that agenda nows what code it must execute. Therefore 3 parameters are passed to the childWorker: name, jobId and path to the job definition.

Example file can look like this:

childWorker.ts

import 'reflect-metadata';

function isCancelMessage(message): message is { type: 'cancel'; error: string } {
    return message !== null && typeof message === 'object' && message.type === 'cancel';
}

(async () => {
    const mongooseConnection = /** connect to database */

  /** do other required initializations */

  // get process arguments (name, jobId and path to agenda definition file)
    const [, , name, jobId, agendaDefinition] = process.argv;

  // set fancy process title
    process.title = `${process.title} (sub worker: ${name}/${jobId})`;

  // initialize Agenda in "forkedWorker" mode
    const agenda = new Agenda({ name: `subworker-${name}`, forkedWorker: true });
    // connect agenda (but do not start it)
    await agenda.mongo(mongooseConnection.db as any);

    if (!name || !jobId) {
        throw new Error(`invalid parameters: ${JSON.stringify(process.argv)}`);
    }

  // load job definition
  /** in this case the file is for example ../some/path/definitions.js
  with a content like:
  export default (agenda: Agenda, definitionOnly = false) => {
    agenda.define(
      'some job',
      async (notification: {
        attrs: { data: { dealId: string; orderId: TypeObjectId<IOrder> } };
      }) => {
        // do something
      }
    );

    if (!definitionOnly) {
        // here you can create scheduled jobs or other things
    }
    });
  */
    if (agendaDefinition) {
        const loadDefinition = await import(agendaDefinition);
        (loadDefinition.default || loadDefinition)(agenda, true);
    }

  // run this job now
    const job = await agenda.getForkedJob(jobId);

  process.on('message', message => {
        if (isCancelMessage(message)) {
            job.cancel(message.error);
            setTimeout(() => {
                // kill it after 10 seconds
                process.exit(2);
            }, 10000);
        } else {
            console.log('got message', message);
        }
    });

    await job.runJob();

  // disconnect database and exit
    process.exit(0);
})().catch(err => {
    console.error('err', err);
    if (process.send) {
        process.send(JSON.stringify(err));
    }
    process.exit(1);
});

Ensure to only define job definitions during this step, otherwise you create some overhead (e.g. if you create new jobs inside the defintion files). That's why I call the defintion file with agenda and a second paramter that is set to true. If this parameter is true, I do not initialize any jobs (create jobs etc..)

2.) to use this, you have to enable it on a job. Set forkMode to true:

const job = agenda.create('some job', { meep: 1 });
job.forkMode(true);
await job.save();

Acknowledgements

License

The MIT License

changelog

Changelog

All notable changes to this project will be documented in this file. See standard-version for commit guidelines.

6.3.0 (2022-12-09)

Features

  • add localLockLimitReached (af90bcb)

Bug Fixes

  • add error message to forked child and give it a chance to die (7cf3c57)

6.2.13 (2022-11-17)

Bug Fixes

  • ready and error events are allowed wihtin sub workers (cb4228c)
  • use definition keys for status list (485060a)

6.2.12 (2022-08-02)

Bug Fixes

  • improve error message for on handler (92d42ca)

6.2.11 (2022-05-23)

Bug Fixes

  • bind correct context to process (cf70739)

6.2.10 (2022-05-23)

Bug Fixes

  • check if lockedAt has been resetted in the meantime (aa5323b)
  • improve errors for childs (8e3b827)

6.2.9 (2022-05-20)

Bug Fixes

  • job timeout check and improve error handling for childs (b365957)

6.2.8 (2022-05-11)

Bug Fixes

  • use message bus instead of signal to cancel child (fcec3a9)

6.2.7 (2022-05-11)

Bug Fixes

  • use different appraoch to find definition file (9d4c60e)

6.2.6 (2022-05-10)

Bug Fixes

  • add fork paramters to console (9f2e7fd)

6.2.5 (2022-05-10)

Bug Fixes

  • improve exit code error message (f1a5eb8)

6.2.4 (2022-05-10)

Bug Fixes

  • check if abort controller is supported (a00d611)

6.2.3 (2022-05-10)

6.2.2 (2022-05-10)

Bug Fixes

  • allow passing forkMode to every (ff274ba)

6.2.1 (2022-05-10)

Bug Fixes

  • small code cleanups and new flag to toggle (2a6e5fe)

6.2.0 (2022-05-09)

Features

  • allow to fork jobs in isolated sub process (2a68c95)

6.1.1 (2022-04-05)

6.1.0 (2022-03-21)

Features

  • check if job state update was successful before running a job (606e141)

6.0.9 (2022-03-18)

6.0.8 (2022-01-10)

6.0.7 (2021-12-12)

6.0.6 (2021-12-10)

Bug Fixes

  • ensure locked at is processed as date (3a5a0c4)

6.0.5 (2021-12-10)

Bug Fixes

  • give the test some more time (e2cacb5)
  • only update job state fields during job processing (be8e51b)

6.0.4 (2021-12-05)

Bug Fixes

  • nextRunAt value can be null (e39cfd0)

6.0.3 (2021-12-03)

Bug Fixes

  • check if job has expired before we run it (e301511)

6.0.2 (2021-10-28)

Bug Fixes

6.0.0 (2021-08-27)

⚠ BREAKING CHANGES

  • Upgrade to mongo driver 4

5.0.1 (2021-02-12)

Bug Fixes

  • update deps and switch moment-timezone to luxon (e5eb973)

5.0.0 (2020-12-06)

⚠ BREAKING CHANGES

  • Switching from ncb000gt/node-cron to harrisiirak/cron-parser for cron-pattern parsing.

    Previously month was 0-based (0=January). Going forward standard Unix pattern is used, which is 1-based (1=January).

    Please update existing cron-patterns that specify a month (4th position of a pattern). The month is now 1 - 12

    1 = January

    2 = February

    3...

    | Example | Execute on 1st of January | |---------|---------------------------| | Old | 0 0 1 0** * | | New | 0 0 1 **1 * |

    old Cron patterns

      * * * * * *
      | | | | | |
      | | | | | +-- Year              (range: 1900-3000)
      | | | | +---- Day of the Week   (range: 1-7, 1 standing for Monday)
      | | | +------ Month of the Year (range: 0-11) NOTE: Difference here
      | | +-------- Day of the Month  (range: 1-31)
      | +---------- Hour              (range: 0-23)
      +------------ Minute            (range: 0-59)

    new cron patterns

      * * * * * *
      | | | | | |
      | | | | | +-- Year              (range: 1900-3000)
      | | | | +---- Day of the Week   (range: 1-7, 1 standing for Monday)
      | | | +------ Month of the Year (range: 1-12) NOTE: Difference here
      | | +-------- Day of the Month  (range: 1-31)
      | +---------- Hour              (range: 0-23)
      +------------ Minute            (range: 0-59)

Co-authored-by: Aras Abbasi a.abbasi@cognigy.com

  • switching from cron to cron-parser (#16) (e5c3bf1)

4.1.6 (2020-11-19)

Bug Fixes

  • only unlock jobs with a next run at date on shutdown (a458aea)

4.1.5 (2020-11-19)

Bug Fixes

  • jobprocessor: ensure set timeout is only called once for each job in the queue (1590224)

4.1.4 (2020-11-18)

Bug Fixes

  • jobprocessor: check if set timeout value is valid (2afaaa3)

4.1.3 (2020-10-30)

Bug Fixes

  • only unlock jobs which have a nextRunAt jobs on shutdown (291f16e)
  • simplify default values (35d5424)

4.1.2 (2020-10-25)

Bug Fixes

  • isRunning for non job processor calls (a5bb965)
  • wait for start of test job (413f797)

4.1.1 (2020-10-25)

Bug Fixes

  • isRunning, check if db returns a result (e6ea7e2)

4.1.0 (2020-10-25)

Features

  • isRunning querys database again if called by client (1aaaa61)

Bug Fixes

  • job processor handling for recurring jobs could fill up queue and block processing (54bc53c)
  • job processor localQueueProcessing flag (413f673)
  • rename err to error, fix typing of DefinitionProcessor, use debug ins… (#9) (39b598e)
  • use isNaN check in isValidDate (#10) (3bc2e30)

4.0.33 (2020-10-24)

Bug Fixes

  • fix outpout of agenda job status details (82ab1a8)
  • fix outpout of agenda job status details (7b24f88)
  • fix outpout of agenda job status details (3dc0709)

4.0.32 (2020-10-24)

Bug Fixes

  • logic for datbase connection (7ee64c1)

4.0.31 (2020-10-23)

Bug Fixes

  • job-processor: emit error when db query fails (9bfabd3)

4.0.30 (2020-10-23)

Bug Fixes

  • job-processor: emit error when db query fails (eff80aa)

4.0.29 (2020-10-22)

Bug Fixes

4.0.28 (2020-10-20)

Bug Fixes

  • tests: rm console log from debugging (b211c8e)

4.0.27 (2020-10-20)

Bug Fixes

  • define: warning if job definition exists already (3fe9a6d)
  • job: ensure agenda is ready before calling save job (be4c026)
  • test: cleanup tests (c5d081a)
  • test: debug failed lock expire test (7d69680)
  • test: debug failed priority test (924287c)
  • test: fix timeout check (e92cd85)
  • typings: names -> name (c2ca928)

4.0.26 (2020-10-20)

Bug Fixes

  • test: just check if there are almost all jobs running (b2a5e6e)

4.0.25 (2020-10-20)

Bug Fixes

  • jobprocessor: check for object.fromEntries for node 10 support (#3) (b8cc61f)
  • jobprocessor: ensure returnNextConcurrencyFreeJob is not returning same job each time (11d6606)
  • jobprocessor: set job enqueud to true for future jobs (a3d4203)
  • test: unlock job test fix (6446b64)
  • more typings, minor functionality changes (#2) (b13d054)

4.0.24 (2020-10-20)

Bug Fixes

  • jobprocessor: improve checkIfJobIsStillAlive (2919083)
  • jobprocessor: prevent overloading of job queue processing (9854007)

4.0.22 (2020-10-16)

Bug Fixes

  • jobprocessor: introduce a canceled property to check if job is still alive (55b63d7)

4.0.21 (2020-10-15)

Features

Bug Fixes

3.1.0 / 2020-04-07

Stay safe!

  • Fix for skipImmediate resetting nextRunAt to current date (#860) (Thanks @AshlinDuncan!)
  • Fix deprecated reconnect options (#948) (Thanks @ekegodigital!)
  • Add ability to set a skip when querying jobs. (#898) (Thanks @cjolif!)

Internal:

  • Fixed deprecated MongoDB functions in tests (#928) (Thanks @MichielDeMey!)
  • Updated devDependencies

Thank you @koresar, @sampathBlam, and @MichielDeMey helping to review PRs for this release! 👏

3.0.0 / 2020-02-13

  • Support MongoDB's Unified Topology Design (#921) (Thanks @viktorzavadil!)
  • Fix: check that the new nextRunAt is different that the previous nextRunAt (#863) (Thanks @RaphaelRheault!)
  • Update dependencies. Most notably MongoDB driver 3.4 → 3.5 (#899, #900, #903, #906, #908, #910, #912, #913, #920, #922)
  • Documentation updates, thanks @MichielDeMey and @Sunghee2. (#923 & #907)

BREAKING

  • Stop testing for Node.js 8. This might still work but we're no longer actively testing for it. (#925)

2.3.0 / 2019-12-16

  • Improved performance in situations when there are many "expired" jobs in the database (#869) (Thanks @mfred488!)
  • Fix periodic node.js process unhandledRejection (#887) (Thanks @koresar and @Scorpil)
  • Update dependencies

2.2.0 / 2019-11-24

  • Fix skipImmediate option in .every (#861) (Thanks @erics2783!)
  • Add try/catch block to agenda#now method (#876) (Thanks @sampathBlam!)
  • Refactor job queuing mechanism. Agenda n ow guarantees priority when executing jobs scheduled the same datetime. Fixes also some tests. (#852) (Thank you @dmbarreiro!)
  • Update dependencies (Kudos @simison!) Most notably mongodb ~3.2.7 -> ~3.3.0 (changelog) — highlights:
    • Mongo DB Server Version 4.2 feature support
    • Merged mongodb-core into node-mongodb-native
    • Beta support for MongoDB Client-Side Encryption
    • SRV Polling for Sharded Clusters
  • Updates to documentation (Thank you @lautarobock, @sampathBlam, @indatawetrust)

2.1.0 / 2019-09-09

  • Support async functions in job processing (#653) (thanks @princjef!)
  • Allow sorting and limiting jobs when searching (#665) (thank you @edwin-jones)
  • Update MongoClient connection settings with useNewUrlParser: true to remove the deprecation warning. (#806) (thanks @dpawson905!)
  • Allow valid date strings when scheduling (#808) (Thanks @wingsbob!)
  • Update dependencies (#820)
  • Update documentation (kudos @dandv, @pedruino and many others!)
  • Fix linting errors (#847) (thanks @dmbarreiro!)

2.0.2 / 2018-09-15

  • Fixes a MongoDB connection string issue with Atlas (#674

2.0.1 / 2018-08-30

  • Fix a bug where job.touch() wasn't promise based, as it should've been (#667

2.0.0 / 2018-07-19

  • Rewrite tests: replace mocha and blanket with ava and nyc (#506)
  • Optimization: don't try and unlock jobs when _lockedJobs is empty (#509)
  • Code cleanup (#503)
  • Ensure tests pass for Node.js version 10 #608)
  • Add skipImmediate to repeatEvery() options to skip immediate run of repeated jobs when Agenda starts. See documentation (#594)
  • Fixes some flaky tests
  • Adds docs generator (npm run docs to generate /docs)

BREAKING

  • Rewrite Agenda API support promises! (#557)

    No more callbacks! Instead of:

    function graceful() {
      agenda.stop(function() {
        process.exit(0);
      });
    }

    You need to:

    async function graceful() {
      await agenda.stop();
      process.exit(0);
    }

    You don't anymore have to listen for start event. Instead you can do:

    await agenda.start();
    agenda.every('10 minutes', 'example');

    However, this will still work:

    agenda.on('ready', function () {
      agenda.every('10 minutes', 'example');
      agenda.start();
    });

    See the documentation for more!

  • Drop support for Node.js versions 4, 5 and 6 (#557 / #608)

  • Drop support for MongoDB 2.4 (#497)
  • Update Native MongoDB driver to 3.1 from 2.2 (#616)
  • Jobs emit errors instead of throwing them

1.0.3 / 2017-10-17

1.0.2 / 2017-10-17

1.0.1 / 2017-10-10

  • Update dependencies cron and debug (#505)

1.0.0 / 2017-08-12

  • Gracefully recover from losing connection to MongoDB (#472)
  • Code cleanup (#492)

BREAKING

Previously Agenda would treat months as 0-11 where as normally, cron months are parsed as 1-12.

* * * * * *
| | | | | |
| | | | | +-- Year              (range: 1900-3000)
| | | | +---- Day of the Week   (range: 1-7, 1 standing for Monday)
| | | +------ Month of the Year (range: 0-11) NOTE: Difference here
| | +-------- Day of the Month  (range: 1-31)
| +---------- Hour              (range: 0-23)
+------------ Minute            (range: 0-59)

Starting in version 1.0.0, cron will be parsed in the standard UNIX style:

* * * * * *
| | | | | |
| | | | | +-- Year              (range: 1900-3000)
| | | | +---- Day of the Week   (range: 1-7, 1 standing for Monday)
| | | +------ Month of the Year (range: 1-12) NOTE: Difference here
| | +-------- Day of the Month  (range: 1-31)
| +---------- Hour              (range: 0-23)
+------------ Minute            (range: 0-59)

0.10.2 / 2017-08-10

0.10.1 / 2017-08-10

  • Unpublished and re-published as v0.10.2

0.10.0 / 2017-08-08

  • Replace the deprecated findAndModify method from native MongoDB driver to findOneAndUpdate (#448)
  • Going forward, we won't ensure Node.js v0.10 and v0.11 compatibility anymore (#449)
  • Code cleanup (#491, #489, #488, #487)

0.9.1 / 2017-03-22

Republish release for NPM. Includes fixes from 0.9.0 release:

  • add support for mongoose.connection for agenda.mongo(), fixes #156
  • Fix for race condition in the afterEach clean up code (#355)
  • Fixes + protects against concurrency not being honored (#379)

0.9.0 / 2016-12-28

  • add support for mongoose.connection for agenda.mongo(), fixes #156
  • Fix for race condition in the afterEach clean up code (#355)
  • Fixes + protects against concurrency not being honored (#379)
  • Bump mongodb dep version to support ssl conns (#368)
  • Increase Mongo compatability to 2.4

0.8.1 / 2016-05-08

  • Add Node v6 to CI
    1. Update dev dependencies for out of date. 2. Small fix to job.js for invalid repeatAt
  • Update .npmignore
  • Fix doc: cb not marked as optional (closes #279)
  • Including nextRunAt check in query for on the fly lock.
  • Picking up any job with an expired lock (not just recurring or queued).
  • Fixed failing test
  • throw on processJobResult error
  • Requeuing concurrency blocked jobs wrt priority.
  • Processing the next job that is not blocked by concurrency.
  • Fix test which fails only sometimes
  • Add agendash as alternative ui
  • Merge pull request #288 from diesal11/master

0.8.0 / 2016-02-21

  • Implementing lock limit
  • Use callback to handle errors if we can.

0.7.9 / 2016-02-05

  • fix: ReferenceError: MongoError is not defined

0.7.8 / 2016-02-03

  • fix: computeNextRunAt timezone bug

0.7.7 / 2016-01-25

  • feat: add timezone option for repeatAt.
  • fix: job locking logic
  • fix: bug with jobs expiring and being enqueued anyway
  • fix: bug where jobs wouldn't run concurrently
  • fix: agenda throwing an exception when starting a job defined on another instance
  • fix: possible bug when using extended Array.prototype

0.7.6 / 2016-01-04

  • feat: Add failCount attribute to jobs
  • fix: job priority for on the fly job lock and queueing is now respected
  • fix: make agenda.cancel no longer require a callback
  • fix: stale jobs running after a more up-to-date job has completed
  • fix: fail/success event emit after jobs have been saved in the database
  • fix: ready event when using config.mongo

0.7.5 / 2015-12-05

  • Adds options.insertOnly to job.unique that prevents the job from being updated multiple times on multiple runs

0.7.4 / 2015-11-26

  • fix job priority scheduling

0.7.3 / 2015-11-22

  • add support for success callbacks on schedule, every and now (@mgregson)
  • using self for reference to collection (@3choBoomer)
  • emit ready from db_init (@jdiamond)

0.7.2 / 2015-10-22

  • Rollback job completion callback to pre-0.7.0
  • Emit events when Agenda init is ready or has failed

0.7.0 / 2015-09-29

  • Switch from mongoskin to mongodb native. Big thanks to the classdojo team for this. Shoutouts to @liamdon, @jetzhou and @byronmwong for the help!

0.6.28 / 2015-02-13

  • Fix for when _findAndLockNextJob returns multiple jobs.

0.6.27 / 2015-02-04

  • code cleanup, fix leaking ignoreErrors

0.6.26 / 2014-11-30

  • fix double run bug

0.6.25 / 2014-11-20

  • Allow specifying mongo config (optionally)

0.6.24 / 2014-10-31

  • Fix .every() running when using cron strings.

0.6.23 / 2014-10-25

  • Remove debugger

0.6.22 / 2014-10-22

  • add job.unique (@nwkeeley)

0.6.21 / 2014-10-20

  • Re-add tests for those who use the npat option.

0.6.20 / 2014-10-14

  • add job.disable() and job.enable()
  • Added .npmignore for test/ build scripts.

0.6.19 / 2014-09-03

  • Create database indexes when initializing Agenda instance (@andyneville)

0.6.18 / 2014-08-16

  • Implemented job.isRunning()
  • Fixed issue where jobs would continue being processed after agenda is explicitly stopped
  • Fixed complete event being emitted before asynchronous jobs are finished

0.6.17 / 2014-08-11

  • add job.repeatAt

0.6.16 / 2014-06-16

  • fix job queue being processed even when agenda was stopped
  • fix agenda.every method

0.6.15 / 2014-06-11

  • fix agenda.every overwriting nextRunAt [closes #70]

0.6.14 / 2014-06-06

  • Added agenda.cancel function
  • Fix more circumstances where jobs re-create after remove

0.6.13 / 2014-06-01

  • fix jobs resaving after remove [closes #66]
  • fix jobs skipping in line from database querying

0.6.12/ 2014-05-22

  • update saveJob to allow for pre-set Ids [closes #64]

0.6.11/ 2014-05-19

  • add job.touch to reset lock lifetime [references #63]

0.6.10 / 2014-05-13

  • make job saving use agenda._name

0.6.9 / 2014-05-13

  • add agenda.name config method
  • fix agenda.mongo not being chainable

0.6.8 / 2014-05-06

  • add graceful job unlocking to stop

0.6.7 / 2014-04-21

  • Implement, document, and test defaultLockLifetime [@shakefu]

0.6.6 / 2014-04-21

  • Bump date.js version [@psema4]

0.6.5 / 2014-04-17

  • mongoskin version bump (better support for mongodb 2.6) [@loginx]

0.6.4 / 2014-04-09

  • fix $setOnInsert with empty obj cause mongodb 2.6 complain [@inetfuture]

0.6.3 / 2014-04-07

  • fix cron-jobs executing multiple times
  • fail the job if repeat interval is wrong

0.6.2 / 2014-03-25

  • fix bug that resulted in jobs scheduled in memory to always re-run
  • Update mongoskin to 1.3

0.6.1 / 2014-03-24

  • allow every and schedule to take array of job names

0.6.0 / 2014-03-21 (NO BREAKING CHANGES)

  • convert to using setTimeout for precise job scheduling [closes #6]

0.5.10/ 2014-03-20

  • fix agenda.every not properly saving jobs
  • improve instantiating jobs, fixes bug where certain attrs weren't loaded in

0.5.9 / 2014-03-10

  • add job#remove method

0.5.8 / 2014-03-07

  • Fixed single jobs not being saved properly [closes #38]

0.5.7 / 2014-03-06

  • fix every re-running jobs out of queue at load

0.5.6 / 2014-02-18

  • Added failing for jobs with undefined definitions
  • Added agenda.purge() to remove old jobs

0.5.5 / 2014-01-28

  • added support to directly give mongoskin object, to help minimize connections

0.5.4 / 2014-01-09

  • Added start event to jobs. (@clayzermki)

0.5.3 / 2014-01-06

  • Added agenda.now method

0.5.2 / 2014-01-06

  • Added ability for job.fail to take an error

0.5.1 / 2013-01-04 (Backwards compatible!)

  • Updated version of humanInterval, adding weeks and months support

0.5.0 / 2013-12-19 (Backwards compatible!)

  • Added job locking mechanism, enabling support for multiple works / agenda instances (@bars3s)

0.4.4 / 2013-12-13

  • fix job.toJson method: add failReason & failedAt attrs (Broken in 0.4.3 and 0.4.2)
  • fix job cb for working with 'q' promises

0.4.3 / 2013-12-13

  • fix job.schedule's taking Date object as 'when' argument [@bars3s]

0.4.2 / 2013-12-11

  • Refactored Job to ensure that everything is stored as an ISODate in the Database. [Closes #14] [@raisch]

0.4.1 / 2013-12-10

  • Added support for synchronous job definitions

0.4.0 / 2013-12-04

  • Added Cron Support [Closes #2]
  • removed modella dependency

0.3.1 / 2013-11-19

  • Fix for setImmediate on Node 0.8

0.3.0 / 2013-11-19

  • Added Events to the Event Queue [References #7]

0.2.1 / 2013-11-14

  • Fixed a bug where mongo wasn't giving updated document

0.2.0 / 2013-11-07

  • Added error for running undefined job. [Closes #4]
  • Fixed critical error where new jobs are not correctly saved.

0.1.3 / 2013-11-06

  • Small Bug fix for global-namespace pollution

0.1.2 / 2013-10-31

  • Updated write concern to avoid annoying notices

0.1.1 / 2013-10-28

  • Removed unecessary UUID code

0.1.0 / 2013-10-28

  • Initial Release