cron vs node-schedule vs node-cron vs agenda vs later
Node.js 定时任务调度库选型指南
cronnode-schedulenode-cronagendalater类似的npm包:
Node.js 定时任务调度库选型指南

agendacronlaternode-cronnode-schedule 都是用于在 Node.js 应用中执行定时或周期性任务的库,但它们在持久化能力、调度语法、依赖项和使用场景上有显著差异。agenda 依赖 MongoDB 实现任务持久化和分布式调度;cronnode-cron 基于 Unix cron 表达式提供轻量级内存调度;later 支持更灵活的调度规则(包括 cron、文本描述和自定义时间逻辑);node-schedule 则使用类似 cron 的 RecurrenceRule 对象,支持日期/时间字段的细粒度控制。这些库适用于从简单脚本到高可靠后台作业系统的不同需求。

npm下载趋势
3 年
GitHub Stars 排名
统计详情
npm包名称
下载量
Stars
大小
Issues
发布时间
License
cron4,367,7288,897161 kB202 个月前MIT
node-schedule3,405,4609,22535 kB1713 年前MIT
node-cron2,291,6723,226221 kB277 个月前ISC
agenda153,3279,626295 kB32 天前MIT
later33,4702,419-9810 年前MIT

Node.js 定时任务调度库深度对比:agenda、cron、later、node-cron 与 node-schedule

在 Node.js 开发中,定时任务无处不在 —— 从每日数据备份、邮件发送到缓存清理。面对 agendacronlaternode-cronnode-schedule 这五个主流库,如何选择?本文从持久化能力、调度语法、API 设计和适用场景出发,为你提供一份实战导向的技术选型指南。

💾 持久化 vs 内存调度:是否需要任务“断电续跑”?

agenda 是唯一支持任务持久化的库,它将任务存储在 MongoDB 中,即使服务重启,未完成的任务仍能恢复执行。其他四个库(cronlaternode-cronnode-schedule)均只在内存中调度,进程退出即丢失所有任务。

// agenda: 任务持久化示例
const agenda = new Agenda({ db: { address: 'mongodb://localhost:27017/agenda' } });

agenda.define('send email', async (job) => {
  await sendEmail(job.attrs.data.to);
});

await agenda.start();
agenda.schedule('in 1 hour', 'send email', { to: 'user@example.com' });
// 即使服务重启,1 小时后任务仍会执行
// cron: 内存调度(无持久化)
const job = new CronJob('0 0 * * *', () => {
  console.log('Daily backup');
}, null, true);
// 若进程退出,任务消失
// later: 同样仅内存调度
const schedule = later.parse.text('every 5 mins');
later.setInterval(() => {
  console.log('Check status');
}, schedule);
// node-cron: 内存调度
const job = new CronJob('*/10 * * * * *', async () => {
  await doSomething();
}, null, true);
// node-schedule: 内存调度
const job = schedule.scheduleJob('0 0 12 * * *', () => {
  console.log('Lunch time!');
});

关键结论:若任务不能丢失(如支付对账、通知发送),必须选 agenda;否则可考虑更轻量的内存方案。

📅 调度语法:cron 表达式、自然语言还是对象配置?

不同库对调度规则的定义方式差异显著,直接影响开发体验。

cronnode-cron 仅支持标准 cron 表达式(5 或 6 位),简洁但不够灵活。

later 支持三种方式:cron 表达式、自然语言(如 'every weekday at 9:00')和自定义时间计算函数,适合复杂业务规则。

node-schedule 使用 RecurrenceRule 对象,允许按字段设置(如 rule.hour = 14; rule.minute = 30),便于程序动态生成规则。

agenda 也支持 cron 表达式,但因其持久化特性,通常配合 schedule() 方法使用绝对时间或相对时间字符串。

// cron: 标准 cron 表达式
new CronJob('0 9 * * 1-5', workdayMorningTask); // 工作日上午 9 点
// later: 自然语言 + 程序化组合
const schedule = later.parse.recur()
  .on(9, 17).hour()        // 9点和17点
  .on(later.Days.MON, later.Days.FRI).dayOfWeek(); // 周一和周五
later.setTimeout(task, schedule);
// node-schedule: 对象式规则
const rule = new schedule.RecurrenceRule();
rule.dayOfWeek = [0, new schedule.Range(1, 5)]; // 周日至周五
rule.hour = 10;
rule.minute = 30;
schedule.scheduleJob(rule, task);
// node-cron: 仅支持 cron 字符串
new CronJob('30 10 * * 0-5', task); // 周日至周五上午 10:30
// agenda: 支持 cron 字符串或自然语言时间
agenda.schedule('today at 2pm', 'task');
agenda.schedule('0 14 * * *', 'task');

关键结论:需要动态生成规则?选 node-schedule;规则复杂且含业务语义?选 later;只需标准 cron?cronnode-cron 足够。

⚙️ API 设计与现代 JavaScript 支持

node-cronagenda 提供了最现代的 API,原生支持 async/await。

cronnode-schedule 的回调函数不直接支持 async,需手动处理 Promise(否则错误会被吞掉)。

later 的 API 较底层,更像工具函数集合,需自行管理任务生命周期。

// node-cron: 原生 async 支持
const job = new CronJob('* * * * * *', async () => {
  await fetch('/api/ping');
});
// agenda: 定义任务时直接使用 async
agenda.define('fetch data', async (job) => {
  const data = await fetchData();
  await saveData(data);
});
// cron: 需手动处理 Promise
new CronJob('* * * * * *', () => {
  fetch('/api/ping').catch(console.error); // 必须 catch,否则静默失败
});
// node-schedule: 同样需手动处理
schedule.scheduleJob('* * * * *', () => {
  someAsyncTask().catch(err => {
    logger.error(err);
  });
});
// later: 无内置任务管理
const timer = later.setTimeout(async () => {
  await doWork();
}, schedule);
// 需自行调用 timer.clear() 取消

关键结论:若大量使用 async/await,优先考虑 node-cronagenda;其他库需格外注意错误处理。

🧩 依赖与部署复杂度

agenda 是唯一有外部依赖的库(MongoDB),增加了部署和运维成本。

其余四个库均为纯 JavaScript 实现,零依赖,可直接嵌入任何 Node.js 项目。

// agenda 需要 MongoDB 连接
const agenda = new Agenda({
  db: { address: process.env.MONGO_URI }
});

cronlaternode-cronnode-schedule 安装后即可使用:

npm install cron
# 无需配置数据库或额外服务

关键结论:若项目无 MongoDB 或希望最小化依赖,避开 agenda;否则其持久化能力值得投入。

🛠️ 任务管理与监控能力

agenda 提供完整的任务生命周期管理:可查询、取消、重试任务,并通过 Web UI(如 agenda-ui)监控状态。

其他库仅提供基础的 start/stop/cancel 接口,无内置状态追踪。

// agenda: 查询待执行任务
const jobs = await agenda.jobs({ name: 'send email' });

// 取消特定任务
await agenda.cancel({ name: 'send email' });

node-cron 仅能通过 job.stop() 停止:

const job = new CronJob(...);
job.start();
// 无法查询历史或状态,只能 stop
job.stop();

关键结论:若需审计、重试或可视化任务,agenda 是唯一选择;否则轻量库足够。

📊 总结:如何选择?

场景推荐库理由
高可靠后台作业系统(需持久化、重试、监控)agenda唯一支持 MongoDB 持久化,任务不丢失
简单 cron 任务,无持久化需求node-cron现代 API,支持 async/await,轻量
熟悉传统 cron,追求极简cron社区最广,API 简单直接
复杂调度规则(如“工作日每小时”)later支持自然语言和程序化规则组合
动态生成调度逻辑(如跳过节假日)node-scheduleRecurrenceRule 对象提供细粒度控制

💡 最终建议

  • 新项目且需持久化 → 选 agenda,尽管有 MongoDB 依赖,但换来的是生产级可靠性。
  • 短期脚本或开发工具 → 选 node-croncron,轻量无负担。
  • 规则复杂但无需持久化 → 用 later 的自然语言解析能力提升可读性。
  • 需要程序动态调整调度时间node-schedule 的对象式规则更灵活。

记住:没有“最好”的库,只有“最合适”当前场景的工具。评估你的需求 —— 是否容忍任务丢失?规则是否复杂?是否已有 MongoDB?—— 答案自然浮现。

如何选择: cron vs node-schedule vs node-cron vs agenda vs later
  • cron:

    选择 cron 如果你只需要一个轻量、无依赖的内存级定时器,且熟悉标准 cron 表达式。它不支持任务持久化或跨进程同步,适合单机、短期运行的脚本或开发环境中的简单调度。由于其 API 简洁且社区广泛,是快速实现基础定时功能的首选。

  • node-schedule:

    选择 node-schedule 如果你需要基于 JavaScript 对象(而非字符串表达式)构建调度规则,并希望精确控制年、月、日、时、分等字段。它支持类似 cron 的功能,但通过 RecurrenceRule 对象提供更强的程序化控制能力,例如动态跳过节假日。所有任务仅在内存中运行,适合需要动态生成调度逻辑但不要求持久化的应用。

  • node-cron:

    选择 node-cron 如果你偏好现代 Promise/async 语法且希望使用标准 cron 表达式。它与 cron 功能相似,但提供了更符合现代 JavaScript 习惯的 API(如 start/stop 方法和 async 回调),同样仅限内存调度。适合希望代码简洁、无需外部依赖的中小型项目。

  • agenda:

    选择 agenda 如果你需要任务持久化、失败重试、任务状态追踪或跨多个实例协调定时任务。它基于 MongoDB 存储任务,适合生产环境中对可靠性要求高的后台作业系统,但会引入数据库依赖和额外运维成本。如果你的应用已使用 MongoDB 且需要长期运行的可恢复任务,它是理想选择。

  • later:

    选择 later 如果你需要比 cron 更灵活的调度规则,比如‘每工作日 9 点到 17 点每 30 分钟执行一次’这类复杂逻辑。它支持 cron 表达式、自然语言描述(如 'every 5 mins')和自定义时间计算,但所有调度都在内存中运行,不提供持久化或分布式支持,适合规则复杂但无需高可用的场景。

cron的README

cron for Node.js logo
cron is a robust tool for running jobs (functions or commands) on schedules defined using the cron syntax.
Perfect for tasks like data backups, notifications, and many more!

Cron for Node.js

Version Monthly Downloads Build Status CodeQL Status Coverage Renovate OpenSSF Scorecard Discord

🌟 Features

  • execute a function whenever your scheduled job triggers
  • execute a job external to the javascript process (like a system command) using child_process
  • use a Date or Luxon DateTime object instead of cron syntax as the trigger for your callback
  • use an additional slot for seconds (leaving it off will default to 0 and match the Unix behavior)

🚀 Installation

npm install cron

Table of Contents

  1. Features
  2. Installation
  3. Migrating
  4. Basic Usage
  5. Cron Patterns
  6. API
  7. Gotchas
  8. Community
  9. Contributing
  10. Acknowledgements
  11. License

⬆ Migrating

v4 dropped Node v16 and renamed the job.running property:

Migrating from v3 to v4

Dropped Node version

Node v16 is no longer supported. Upgrade your Node installation to Node v18 or above

Property renamed and now read-only

You can no longer set the running property (now isActive). It is read-only. To start or stop a cron job, use job.start() and job.stop().

v3 introduced TypeScript and tighter Unix cron pattern alignment:

Migrating from v2 to v3

Month & day-of-week indexing changes

  • Month Indexing: Changed from 0-11 to 1-12. So you need to increment all numeric months by 1.

  • Day-of-Week Indexing: Support added for 7 as Sunday.

Adjustments in CronJob

  • The constructor no longer accepts an object as its first and only params. Use CronJob.from(argsObject) instead.
  • Callbacks are now called in the order they were registered.
  • nextDates(count?: number) now always returns an array (empty if no argument is provided). Use nextDate() instead for a single date.

Removed methods

  • removed job() method in favor of new CronJob(...args) / CronJob.from(argsObject)

  • removed time() method in favor of new CronTime()

🛠 Basic Usage

import { CronJob } from 'cron';

const job = new CronJob(
	'* * * * * *', // cronTime
	function () {
		console.log('You will see this message every second');
	}, // onTick
	null, // onComplete
	true, // start
	'America/Los_Angeles' // timeZone
);
// job.start() is optional here because of the fourth parameter set to true.
// equivalent job using the "from" static method, providing parameters as an object
const job = CronJob.from({
	cronTime: '* * * * * *',
	onTick: function () {
		console.log('You will see this message every second');
	},
	start: true,
	timeZone: 'America/Los_Angeles'
});

Note: In the first example above, the fourth parameter to CronJob() starts the job automatically. If not provided or set to falsy, you must explicitly start the job using job.start().

For more advanced examples, check the examples directory.

⏰ Cron Patterns

Cron patterns are the backbone of this library. Familiarize yourself with the syntax:

- `*` Asterisks: Any value
- `1-3,5` Ranges: Ranges and individual values
- `*/2` Steps: Every two units

Detailed patterns and explanations are available at crontab.org. The examples in the link have five fields, and 1 minute as the finest granularity, but our cron scheduling supports an enhanced format with six fields, allowing for second-level precision. Tools like crontab.guru can help in constructing patterns but remember to account for the seconds field.

Supported Ranges

Here's a quick reference to the UNIX Cron format this library uses, plus an added second field:

field          allowed values
-----          --------------
second         0-59
minute         0-59
hour           0-23
day of month   1-31
month          1-12 (or names, see below)
day of week    0-7 (0 or 7 is Sunday, or use names)

Names can also be used for the 'month' and 'day of week' fields. Use the first three letters of the particular day or month (case does not matter). Ranges and lists of names are allowed.
Examples: "mon,wed,fri", "jan-mar".

📖 API

Standalone Functions

  • sendAt: Indicates when a CronTime will execute (returns a Luxon DateTime object).

    import * as cron from 'cron';
    
    const dt = cron.sendAt('0 0 * * *');
    console.log(`The job would run at: ${dt.toISO()}`);
    
  • timeout: Indicates the number of milliseconds in the future at which a CronTime will execute (returns a number).

    import * as cron from 'cron';
    
    const timeout = cron.timeout('0 0 * * *');
    console.log(`The job would run in ${timeout}ms`);
    
  • validateCronExpression: Validates if a given cron expression is valid (returns an object with valid and error properties).

    import * as cron from 'cron';
    
    const validation = cron.validateCronExpression('0 0 * * *');
    console.log(`Is the cron expression valid? ${validation.valid}`);
    if (!validation.valid) {
    	console.error(`Validation error: ${validation.error}`);
    }
    

CronJob Class

Constructor

constructor(cronTime, onTick, onComplete, start, timeZone, context, runOnInit, utcOffset, unrefTimeout, waitForCompletion, errorHandler, name, threshold):

  • cronTime: [REQUIRED] - The time to fire off your job. Can be cron syntax, a JS Date object or a Luxon DateTime object.

  • onTick: [REQUIRED] - Function to execute at the specified time. If an onComplete callback was provided, onTick will receive it as an argument.

  • onComplete: [OPTIONAL] - Invoked when the job is halted with job.stop(). It might also be triggered by onTick post its run.

  • start: [OPTIONAL] - Determines if the job should commence before constructor exit. Default is false.

  • timeZone: [OPTIONAL] - Sets the execution time zone. Default is local time. Check valid formats in the Luxon documentation.

  • context: [OPTIONAL] - Execution context for the onTick method.

  • runOnInit: [OPTIONAL] - Instantly triggers the onTick function post initialization. Default is false.

  • utcOffset: [OPTIONAL] - Specifies time zone offset in minutes. Cannot co-exist with timeZone.

  • unrefTimeout: [OPTIONAL] - Useful for controlling event loop behavior. More details here.

  • waitForCompletion: [OPTIONAL] - If true, no additional instances of the onTick callback function will run until the current onTick callback has completed. Any new scheduled executions that occur while the current callback is running will be skipped entirely. Default is false.

  • errorHandler: [OPTIONAL] - Function to handle any exceptions that occur in the onTick method.

  • name: [OPTIONAL] - Name of the job. Useful for identifying jobs in logs.

  • threshold: [OPTIONAL] - Threshold in ms to control whether to execute or skip missed execution deadlines caused by slow or busy hardware. Execution delays within threshold will be executed immediately, and otherwise will be skipped. In both cases a warning will be printed to the console with the job name and cron expression. See issue #962 for more information. Default is 250.

Methods

  • from (static): Create a new CronJob object providing arguments as an object. See argument names and descriptions above.

  • start: Initiates the job.

  • stop: Halts the job.

  • setTime: Modifies the time for the CronJob. Parameter must be a CronTime.

  • lastDate: Provides the last execution date.

  • nextDate: Indicates the subsequent date that will activate an onTick.

  • nextDates(count): Supplies an array of upcoming dates that will initiate an onTick.

  • fireOnTick: Allows modification of the onTick calling behavior.

  • addCallback: Permits addition of onTick callbacks.

Properties

  • isActive: [READ-ONLY] Indicates if a job is active (checking to see if the callback needs to be called).

  • isCallbackRunning: [READ-ONLY] Indicates if a callback is currently executing.

    const job = new CronJob('* * * * * *', async () => {
    	console.log(job.isCallbackRunning); // true during callback execution
    	await someAsyncTask();
    	console.log(job.isCallbackRunning); // still true until callback completes
    });
    
    console.log(job.isCallbackRunning); // false
    job.start();
    console.log(job.isActive); // true
    console.log(job.isCallbackRunning); // false
    

CronTime Class

Constructor

constructor(time, zone, utcOffset):

  • time: [REQUIRED] - The time to initiate your job. Accepts cron syntax or a JS Date object.

  • zone: [OPTIONAL] - Equivalent to timeZone from CronJob parameters.

  • utcOffset: [OPTIONAL] - Analogous to utcOffset from CronJob parameters.

💢 Gotchas

  • Both JS Date and Luxon DateTime objects don't guarantee millisecond precision due to computation delays. This module excludes millisecond precision for standard cron syntax but allows execution date specification through JS Date or Luxon DateTime objects. However, specifying a precise future execution time, such as adding a millisecond to the current time, may not always work due to these computation delays. It's observed that delays less than 4-5 ms might lead to inconsistencies. While we could limit all date granularity to seconds, we've chosen to allow greater precision but advise users of potential issues.

  • Using arrow functions for onTick binds them to the parent's this context. As a result, they won't have access to the cronjob's this context. You can read a little more in issue #47 (comment).

🤝 Community

Join the Discord server! Here you can discuss issues and get help in a more casual forum than GitHub.

🌍 Contributing

This project is looking for help! If you're interested in helping with the project, please take a look at our contributing documentation.

🐛 Submitting Bugs/Issues

Please have a look at our contributing documentation, it contains all the information you need to know before submitting an issue.

🙏 Acknowledgements

This is a community effort project. In the truest sense, this project started as an open source project from cron.js and grew into something else. Other people have contributed code, time, and oversight to the project. At this point there are too many to name here so we'll just say thanks.

Special thanks to Hiroki Horiuchi, Lundarl Gholoi and koooge for their work on the DefinitelyTyped typings before they were imported in v2.4.0.

⚖ License

MIT