node-schedule vs agenda vs bull
Background Job Processing and Task Scheduling in Node.js
node-scheduleagendabullSimilar Packages:

Background Job Processing and Task Scheduling in Node.js

agenda, bull, and node-schedule are Node.js libraries designed to handle delayed tasks, recurring jobs, and background processing. agenda uses MongoDB to store job data, offering persistence and distributed locking. bull relies on Redis for high-performance queue management with priority support. node-schedule runs entirely in memory using cron syntax, making it lightweight but limited to single-process environments. These tools help developers move heavy tasks off the main thread to keep applications responsive.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
node-schedule4,788,0159,19735.3 kB17311 days agoMIT
agenda212,2759,714310 kB194 days agoMIT
bull016,262309 kB1472 years agoMIT

Agenda vs Bull vs Node-Schedule: Architecture, Persistence, and Scale

When building full-stack Node.js applications, frontend developers often need to offload heavy tasks β€” like sending emails, generating reports, or syncing data β€” to background workers. agenda, bull, and node-schedule solve this problem differently. Let's compare how they handle storage, job definition, and reliability.

πŸ’Ύ Storage & Persistence: Database vs Cache vs Memory

Where jobs are stored determines if you lose work when the server restarts.

agenda stores every job in MongoDB.

  • Jobs persist even if the process crashes.
  • Multiple servers can share the same database to distribute work.
// agenda: MongoDB persistence
const agenda = new Agenda({ db: { address: 'mongodb://localhost/agenda' } });
await agenda.start();
// Jobs are saved in 'agendaJobs' collection automatically

bull stores job state in Redis.

  • Redis is faster than Mongo but still external.
  • Jobs survive restarts as long as Redis persists data.
// bull: Redis persistence
const Queue = require('bull');
const queue = new Queue('email-queue', 'redis://127.0.0.1:6379');
// Job data is stored in Redis keys automatically

node-schedule keeps jobs in server memory.

  • All jobs vanish if the process stops or crashes.
  • No external connection needed, but no safety net.
// node-schedule: In-memory only
const schedule = require('node-schedule');
// Jobs exist only while this Node process is running

πŸ“ Defining Work: Named Jobs vs Queue Processors vs Functions

How you write the code that actually runs changes based on the library.

agenda uses named definitions.

  • You define a job name once, then schedule it by name.
  • Useful when different parts of the app trigger the same task.
// agenda: Define by name
agenda.define('send-welcome-email', async (job) => {
  const { email } = job.attrs.data;
  await sendEmail(email);
});

// Trigger elsewhere
agenda.schedule('in 5 minutes', 'send-welcome-email', { email: '[email protected]' });

bull uses queue processors.

  • You attach a handler function to a specific queue.
  • Data is passed directly when adding to the queue.
// bull: Process queue
queue.process(async (job) => {
  const { email } = job.data;
  await sendEmail(email);
});

// Trigger elsewhere
await queue.add({ email: '[email protected]' });

node-schedule uses direct functions.

  • You pass the function directly to the scheduler.
  • Simplest setup, but harder to manage complex data flow.
// node-schedule: Direct function
const job = schedule.scheduleJob('*/5 * * * *', async () => {
  await cleanupTempFiles();
});

⏱️ Scheduling & Recurrence: Flexibility vs Cron

All three handle timing, but their syntax and capabilities differ.

agenda supports natural language and dates.

  • You can say "in 5 minutes" or pass a specific Date object.
  • Also supports cron strings for repeating jobs.
// agenda: Natural language & Cron
agenda.schedule('in 5 minutes', 'job-name', { data });
agenda.every('5 minutes', 'job-name'); // Repeating

bull focuses on delays and cron.

  • You specify a delay in milliseconds or a cron pattern.
  • Great for precise timing control.
// bull: Delay & Cron
await queue.add({ data }, { delay: 300000 }); // 5 mins
await queue.add({ data }, { repeat: { cron: '*/5 * * * *' } });

node-schedule is built for cron syntax.

  • Uses standard cron strings or Date objects.
  • Very familiar to developers who know Linux cron.
// node-schedule: Cron & Date
schedule.scheduleJob('*/5 * * * *', () => {}); // Every 5 mins
schedule.scheduleJob(new Date(2024, 1, 1, 0, 0), () => {}); // Specific date

πŸ›‘οΈ Reliability & Crash Recovery: What Happens When It Fails?

Production systems crash. Your job runner should handle it.

agenda locks jobs while running.

  • If a server dies, the lock expires and another server picks it up.
  • Ensures jobs are not lost or duplicated across clusters.
// agenda: Automatic locking
// If process dies mid-job, lock releases after timeout
// Another instance will grab the job automatically

bull has built-in retries and backoffs.

  • You can configure how many times to retry failed jobs.
  • Moves failed jobs to a special "failed" queue for inspection.
// bull: Retry configuration
queue.process(async (job) => { /* ... */ });
// Configured when adding job
await queue.add({ data }, { attempts: 3, backoff: { type: 'exponential', delay: 1000 } });

node-schedule has no built-in recovery.

  • If the function throws, the job simply stops.
  • You must write your own try/catch and logging logic.
// node-schedule: Manual error handling
schedule.scheduleJob('*/1 * * * *', async () => {
  try {
    await riskyTask();
  } catch (err) {
    console.error('Job failed', err); // Must handle manually
  }
});

🌐 Scaling & Environment: Clusters vs Serverless

Your deployment model dictates which tool fits.

agenda scales across multiple nodes.

  • Multiple servers can run the same code.
  • MongoDB acts as the coordinator to prevent double-work.
// agenda: Multi-server safe
// Server A and Server B both connect to same Mongo
// Only one executes the job at a time

bull scales horizontally with Redis.

  • Many workers can listen to the same queue.
  • Redis distributes jobs to available workers efficiently.
// bull: Multi-worker safe
// Multiple Node processes connect to same Redis
// Jobs are distributed round-robin style

node-schedule works on single instances only.

  • Do not use in serverless functions (AWS Lambda, Vercel).
  • Do not use in clustered apps without external coordination.
// node-schedule: Single instance only
// If you run 5 servers, the job runs 5 times simultaneously

πŸ“Š Summary: Key Differences

Featureagendabullnode-schedule
StorageπŸ—„οΈ MongoDB⚑ Redis🧠 In-Memory
Persistenceβœ… Survives restartsβœ… Survives restarts❌ Lost on restart
SchedulingπŸ“… Natural language & Cron⏱️ Delay & CronπŸ•’ Cron & Date
Scaling🌐 Multi-server safe🌐 Multi-server safeπŸ–₯️ Single server only
Error HandlingπŸ”’ Auto-lock & retryπŸ”„ Configurable retries⚠️ Manual try/catch
Best ForMongo stacks, distributed jobsHigh throughput, Redis stacksSimple cron, single server

πŸ’‘ Final Recommendation

agenda is the right choice if you are already using MongoDB and need reliable, distributed job processing without adding new infrastructure. It handles locking and persistence well, though it can be slower than Redis-based solutions.

bull is the industry standard for high-performance queues. If you have Redis or can add it, this offers the best speed and flexibility. Keep in mind that bullmq is the modern successor, but bull remains stable for existing projects.

node-schedule is perfect for simple, low-stakes tasks on a single server. Use it for internal maintenance scripts or local development tools. Avoid it for critical user-facing workflows or cloud functions where processes spin up and down frequently.

Final Thought: For most production full-stack apps, bull provides the best balance of speed and reliability. If you want to avoid Redis, agenda is a solid alternative. Reserve node-schedule for lightweight, non-critical automation.

How to Choose: node-schedule vs agenda vs bull

  • node-schedule:

    Choose node-schedule for simple cron tasks running on a single server where persistence is not critical. It is perfect for lightweight maintenance jobs like cleanup scripts or internal health checks. Avoid this for serverless environments or clusters since jobs do not survive process restarts.

  • agenda:

    Choose agenda if your stack already uses MongoDB and you need persistent jobs that survive server restarts. It is ideal for distributed systems where multiple nodes need to coordinate work without duplicate execution. However, it requires a database connection and adds latency compared to in-memory solutions.

  • bull:

    Choose bull if you need high throughput, priority queues, or have Redis available in your infrastructure. It handles large volumes of jobs efficiently and offers robust retry mechanisms. Note that while bull is stable, the newer bullmq is the active development branch for modern projects.

README for node-schedule

Node Schedule

NPM version Downloads Build Status Coverage Status Join the chat at https://gitter.im/node-schedule/node-schedule

NPM

Node Schedule is a flexible cron-like and not-cron-like job scheduler for Node.js. It allows you to schedule jobs (arbitrary functions) for execution at specific dates, with optional recurrence rules. It only uses a single timer at any given time (rather than reevaluating upcoming jobs every second/minute).

Node 6+ is supported.

Overview

Node Schedule is for time-based scheduling, not interval-based scheduling.

While you can easily bend it to your will, if you only want to do something like "run this function every 5 minutes", toad-scheduler would be a better choice. But if you want to, say, "run this function at the :20 and :50 of every hour on the third Tuesday of every month," you'll find that Node Schedule suits your needs better. Additionally, Node Schedule has Windows support, unlike true cron, since the node runtime is now fully supported.

Note that Node Schedule is designed for in-process scheduling, i.e. scheduled jobs will only fire as long as your script is running, and the schedule will disappear when execution completes. If you need to schedule jobs that will persist even when your script isn't running, consider using actual cron.

In case you need durable jobs that persist across restarts and lock system compatible with multi-node deployments, try agenda or bree.

Usage

Installation

You can install using npm.

npm install node-schedule

Jobs and Scheduling

Every scheduled job in Node Schedule is represented by a Job object. You can create jobs manually, then execute the schedule() method to apply a schedule, or use the convenience function scheduleJob() as demonstrated below.

Job objects are EventEmitters, and emit the following events:

  • A run event after each execution.
  • A scheduled event each time they're scheduled to run.
  • A canceled event when an invocation is canceled before it's executed.
    Note that canceled is the single-L American spelling.
  • An error event when a job invocation triggered by a schedule throws or returns a rejected Promise.
  • A success event when a job invocation triggered by a schedule returns successfully or returns a resolved Promise. In any case, the success event receives the value returned by the callback or in case of a promise, the resolved value.

(Both the scheduled and canceled events receive a JavaScript date object as a parameter).
Note that jobs are scheduled the first time immediately, so if you create a job using the scheduleJob() convenience method, you'll miss the first scheduled event, but you can query the invocation manually (see below).

Cron-style Scheduling

The cron format consists of:

*    *    *    *    *    *
┬    ┬    ┬    ┬    ┬    ┬
β”‚    β”‚    β”‚    β”‚    β”‚    β”‚
β”‚    β”‚    β”‚    β”‚    β”‚    β”” day of week (0 - 7) (0 or 7 is Sun)
β”‚    β”‚    β”‚    β”‚    └───── month (1 - 12)
β”‚    β”‚    β”‚    └────────── day of month (1 - 31)
β”‚    β”‚    └─────────────── hour (0 - 23)
β”‚    └──────────────────── minute (0 - 59)
└───────────────────────── second (0 - 59, OPTIONAL)

Examples with the cron format:

const schedule = require('node-schedule');

const job = schedule.scheduleJob('42 * * * *', function(){
  console.log('The answer to life, the universe, and everything!');
});

Execute a cron job when the minute is 42 (e.g. 19:42, 20:42, etc.).

And:

const job = schedule.scheduleJob('0 17 ? * 0,4-6', function(){
  console.log('Today is recognized by Rebecca Black!');
});

Execute a cron job every 5 Minutes = */5 * * * *

You can also get when it is scheduled to run for every invocation of the job:

const job = schedule.scheduleJob('0 1 * * *', function(fireDate){
  console.log('This job was supposed to run at ' + fireDate + ', but actually ran at ' + new Date());
});

This is useful when you need to check if there is a delay of the job invocation when the system is busy, or save a record of all invocations of a job for audit purpose.

Unsupported Cron Features

Currently, W (nearest weekday) and L (last day of month/week) are not supported. Most other features supported by popular cron implementations should work just fine, including # (nth weekday of the month).

cron-parser is used to parse crontab instructions.

Date-based Scheduling

Say you very specifically want a function to execute at 5:30am on December 21, 2012. Remember - in JavaScript - 0 - January, 11 - December.

const schedule = require('node-schedule');
const date = new Date(2012, 11, 21, 5, 30, 0);

const job = schedule.scheduleJob(date, function(){
  console.log('The world is going to end today.');
});

To use current data in the future you can use binding:

const schedule = require('node-schedule');
const date = new Date(2012, 11, 21, 5, 30, 0);
const x = 'Tada!';
const job = schedule.scheduleJob(date, function(y){
  console.log(y);
}.bind(null,x));
x = 'Changing Data';

This will log 'Tada!' when the scheduled Job runs, rather than 'Changing Data', which x changes to immediately after scheduling.

Recurrence Rule Scheduling

You can build recurrence rules to specify when a job should recur. For instance, consider this rule, which executes the function every hour at 42 minutes after the hour:

const schedule = require('node-schedule');

const rule = new schedule.RecurrenceRule();
rule.minute = 42;

const job = schedule.scheduleJob(rule, function(){
  console.log('The answer to life, the universe, and everything!');
});

You can also use arrays to specify a list of acceptable values, and the Range object to specify a range of start and end values, with an optional step parameter. For instance, this will print a message on Thursday, Friday, Saturday, and Sunday at 5pm:

const rule = new schedule.RecurrenceRule();
rule.dayOfWeek = [0, new schedule.Range(4, 6)];
rule.hour = 17;
rule.minute = 0;

const job = schedule.scheduleJob(rule, function(){
  console.log('Today is recognized by Rebecca Black!');
});

Timezones are also supported. Here is an example of executing at the start of every day in the UTC timezone.

const rule = new schedule.RecurrenceRule();
rule.hour = 0;
rule.minute = 0;
rule.tz = 'Etc/UTC';

const job = schedule.scheduleJob(rule, function(){
  console.log('A new day has begun in the UTC timezone!');
});

A list of acceptable tz (timezone) values can be found at https://en.wikipedia.org/wiki/List_of_tz_database_time_zones

RecurrenceRule properties

  • second (0-59)
  • minute (0-59)
  • hour (0-23)
  • date (1-31)
  • month (0-11)
  • year
  • dayOfWeek (0-6) Starting with Sunday
  • tz

Note: It's worth noting that the default value of a component of a recurrence rule is null (except for second, which is 0 for familiarity with cron). If we did not explicitly set minute to 0 above, the message would have instead been logged at 5:00pm, 5:01pm, 5:02pm, ..., 5:59pm. Probably not what you want.

Object Literal Syntax

To make things a little easier, an object literal syntax is also supported, like in this example which will log a message every Sunday at 2:30pm:

const job = schedule.scheduleJob({hour: 14, minute: 30, dayOfWeek: 0}, function(){
  console.log('Time for tea!');
});

Set StartTime and EndTime

It will run after 5 seconds and stop after 10 seconds in this example. The ruledat supports the above.

const startTime = new Date(Date.now() + 5000);
const endTime = new Date(startTime.getTime() + 5000);
const job = schedule.scheduleJob({ start: startTime, end: endTime, rule: '*/1 * * * * *' }, function(){
  console.log('Time for tea!');
});

Graceful Shutdown.

You can shutdown jobs gracefully.
gracefulShutdown() will cancel all jobs and return Promise.
It will wait until all jobs are terminated.

schedule.gracefulShutdown();

You can also gracefully shutdown jobs when a system interrupt occurs.

process.on('SIGINT', function () { 
  schedule.gracefulShutdown()
  .then(() => process.exit(0))
}

Handle Jobs and Job Invocations

There are some function to get information for a Job and to handle the Job and Invocations.

job.cancel(reschedule)

You can invalidate any job with the cancel() method:

j.cancel();

All planned invocations will be canceled. When you set the parameter reschedule to true then the Job is newly scheduled afterwards.

job.cancelNext(reschedule)

This method invalidates the next planned invocation or the job. When you set the parameter reschedule to true then the Job is newly scheduled afterwards.

job.reschedule(spec)

This method cancels all pending invocation and registers the Job completely new again using the given specification. Return true/false on success/failure.

job.nextInvocation()

This method returns a Date object for the planned next Invocation for this Job. If no invocation is planned the method returns null.

Contributing

This module was originally developed by Matt Patenaude who eventually passed over maintainer's mantle over to Tejas Manohar.

Currently it is being maintained by Igor Savin and our amazing community.

We'd love to get your contributions. Individuals making significant and valuable contributions are given commit-access to the project to contribute as they see fit.

Before jumping in, check out our Contributing page guide!

Copyright and license

Copyright 2015 Matt Patenaude.

Licensed under the MIT License.