agenda、bull 和 node-schedule 都是 Node.js 生态中用于处理定时任务和后台作业的经典库,但它们的底层架构和适用场景截然不同。node-schedule 是一个基于内存的 Cron 风格调度器,适合简单的进程内定时任务。agenda 基于 MongoDB 存储任务,支持持久化和复杂的重试逻辑,适合需要数据持久化的场景。bull 基于 Redis 构建,专注于高性能的任务队列,支持优先级、并发控制和分布式处理。选择哪个库取决于你的项目是否需要任务持久化、是否涉及分布式部署以及对依赖基础设施的偏好。
在 Node.js 后端开发中,处理定时任务(如每日报表)和后台作业(如发送邮件)是常见需求。agenda、bull 和 node-schedule 提供了三种不同的解决思路。它们的核心区别在于任务存储方式、执行模型以及对基础设施的依赖。让我们从架构师的视角,深入对比它们在真实工程中的表现。
node-schedule 完全运行在进程内存中。
// node-schedule: 内存中的定时任务
const schedule = require('node-schedule');
const job = schedule.scheduleJob('*/5 * * * *', () => {
console.log('每 5 分钟执行一次');
});
agenda 将任务存储在 MongoDB 中。
// agenda: 基于 MongoDB 的任务
const { Agenda } = require('agenda');
const agenda = new Agenda({ db: { address: 'mongodb://localhost/agenda' } });
agenda.define('发送报告', async (job) => {
await sendReport(job.attrs.data);
});
await agenda.schedule('in 10 minutes', '发送报告', { userId: 123 });
await agenda.start();
bull 基于 Redis 实现队列。
// bull: 基于 Redis 的队列
const Queue = require('bull');
const emailQueue = new Queue('email', 'redis://127.0.0.1:6379');
emailQueue.process(async (job) => {
await sendEmail(job.data);
});
emailQueue.add({ to: '[email protected]' }, { attempts: 3 });
node-schedule 严格遵循 Cron 语法。
// node-schedule: 标准 Cron 表达式
// 每天凌晨 2 点执行
schedule.scheduleJob('0 2 * * *', () => {
cleanupDatabase();
});
agenda 支持 Cron 和相对时间。
in 5 minutes 这样的自然语言风格。// agenda: 支持相对时间
// 5 分钟后执行
agenda.schedule('in 5 minutes', '任务名', { data: 1 });
// 或每天执行
agenda.every('1 day', '任务名');
bull 专注于队列添加,定时需配合延迟。
delay 选项实现。repeat 配置。// bull: 延迟与重复任务
// 延迟 5000 毫秒执行
queue.add({ id: 1 }, { delay: 5000 });
// 每 24 小时重复
queue.add({}, { repeat: { cron: '0 0 * * *' } });
node-schedule 无持久化能力。
// node-schedule: 重启后任务消失
// 无内置恢复机制,需自行实现数据库标记
agenda 自动恢复未完成任务。
// agenda: 自动恢复
// start() 调用后会自动处理数据库中 lockAt 过期的任务
await agenda.start();
bull 提供完善的失败重试机制。
// bull: 重试配置
queue.add(data, {
attempts: 3,
backoff: { type: 'exponential', delay: 1000 }
});
node-schedule 单进程限制。
// node-schedule: 单线程阻塞风险
schedule.scheduleJob('* * * * *', async () => {
await heavyTask(); // 阻塞后续任务
});
agenda 支持多实例锁机制。
agenda.start() 时,Mongo 锁确保任务只被执行一次。// agenda: 多实例安全
// 多个节点运行相同代码,Mongo 锁防止重复执行
const agenda = new Agenda({ db: { address: uri } });
await agenda.start();
bull 原生支持分布式并发。
// bull: 并发控制
queue.process(5, async (job) => {
// 最多同时处理 5 个任务
await processJob(job);
});
| 特性 | node-schedule | agenda | bull |
|---|---|---|---|
| 存储引擎 | 内存 | MongoDB | Redis |
| 持久化 | ❌ 无 | ✅ 有 | ✅ 有 |
| 重启恢复 | ❌ 丢失 | ✅ 自动恢复 | ✅ 自动重试 |
| 分布式支持 | ❌ 不支持 | ✅ 支持 (锁机制) | ✅ 支持 (队列竞争) |
| 外部依赖 | 无 | MongoDB | Redis |
| 适用场景 | 简单定时任务 | 复杂业务作业 | 高并发消息队列 |
node-schedule 像是一个简单的闹钟 ⏰ —— 适合个人工具、开发环境或无需持久化的轻量级定时检查。如果你的应用部署在 Serverless 环境或无状态容器,请避免使用它。
agenda 像是一个带记录本的管家 📒 —— 适合业务逻辑复杂、需要查询任务历史、且已经使用 MongoDB 的团队。它在任务状态管理上非常灵活,但性能受限于数据库。
bull 像是一个高效的流水线 🏭 —— 适合生产环境的核心后台任务。如果你需要高可用、高并发和完善的失败处理,Redis 驱动的 bull 是行业标准选择。
核心决策点:先看基础设施 —— 有 Redis 选 bull,有 Mongo 选 agenda,啥都没有且任务不重要选 node-schedule。
如果你的任务简单、无需持久化,且希望零外部依赖(无需 Redis 或 Mongo),node-schedule 最轻量。它适合单进程应用中的定时清理、健康检查或本地 Cron 任务。但在多实例部署或重启敏感场景下需谨慎使用。
如果你的项目已经使用 MongoDB 作为主要数据库,且需要任务在服务器重启后不丢失,agenda 是自然的选择。它将任务定义和调度数据直接存储在 Mongo 集合中,方便查询和管理历史任务。适合中等复杂度、需要持久化保障的后台作业场景。
如果你需要高性能、高并发的任务处理能力,或者计划进行分布式部署,bull 是更优的方案。它基于 Redis,支持任务优先级、延迟队列和失败重试,且社区生态丰富。适合消息队列、视频处理、邮件发送等需要可靠投递的生产环境。
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.
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.
You can install using npm.
npm install node-schedule
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:
run event after each execution.scheduled event each time they're scheduled to run.canceled event when an invocation is canceled before it's executed.canceled is the single-L American spelling.error event when a job invocation triggered by a schedule throws or returns
a rejected Promise.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).
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.
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.
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.
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
second (0-59)minute (0-59)hour (0-23)date (1-31)month (0-11)yeardayOfWeek (0-6) Starting with SundaytzNote: 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 setminuteto 0 above, the message would have instead been logged at 5:00pm, 5:01pm, 5:02pm, ..., 5:59pm. Probably not what you want.
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!');
});
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!');
});
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))
}
There are some function to get information for a Job and to handle the Job and Invocations.
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.
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.
This method cancels all pending invocation and registers the Job completely new again using the given specification. Return true/false on success/failure.
This method returns a Date object for the planned next Invocation for this Job. If no invocation is planned the method returns null.
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 2015 Matt Patenaude.
Licensed under the MIT License.