agenda vs cron vs later vs node-schedule
Node.js 定时任务库
agendacronlaternode-schedule类似的npm包:

Node.js 定时任务库

Node.js 定时任务库用于在服务器端执行定时任务或调度任务。这些库提供了灵活的方式来安排任务在特定时间或间隔内执行,适用于需要定期执行的后台任务,如发送电子邮件、清理数据库或生成报告等。选择合适的定时任务库可以提高应用程序的效率和可维护性,同时确保任务按预期执行。

npm下载趋势

3 年

GitHub Stars 排名

统计详情

npm包名称
下载量
Stars
大小
Issues
发布时间
License
agenda09,660297 kB36 小时前MIT
cron08,923161 kB285 个月前MIT
later02,417-9811 年前MIT
node-schedule09,21035 kB1713 年前MIT

功能对比: agenda vs cron vs later vs node-schedule

调度灵活性

  • agenda:

    Agenda 提供了丰富的调度选项,支持复杂的任务调度和重复任务。它允许你定义任务的执行时间、频率和条件,非常适合需要持久化和高可靠性的任务。

  • cron:

    Cron 的调度方式基于 UNIX 的 cron 表达式,适合简单的定时任务。它的灵活性较低,但对于简单的定时需求来说非常有效。

  • later:

    Later 提供了极高的调度灵活性,支持多种时间格式和自然语言描述。你可以轻松定义复杂的调度规则,非常适合需要高度自定义的场景。

  • node-schedule:

    Node-schedule 支持 cron 表达式和 JavaScript 日期对象,提供了良好的调度灵活性,适合大多数常见的定时任务需求。

持久化支持

  • agenda:

    Agenda 内置了对 MongoDB 的支持,可以持久化任务状态和调度信息,确保任务在服务器重启后依然能够恢复执行。

  • cron:

    Cron 不支持持久化,任务状态在服务器重启后会丢失,适合简单的、短期的定时任务。

  • later:

    Later 不提供持久化支持,适合临时的调度需求,任务状态不会被保存。

  • node-schedule:

    Node-schedule 也不支持持久化,适合简单的定时任务,任务状态在服务器重启后会丢失。

学习曲线

  • agenda:

    Agenda 的学习曲线相对较陡,需要了解 MongoDB 和其 API,适合需要复杂调度的开发者。

  • cron:

    Cron 的学习曲线较平缓,熟悉 UNIX 的开发者可以快速上手,适合简单的定时任务。

  • later:

    Later 的学习曲线适中,支持自然语言描述时间,适合需要灵活调度的开发者。

  • node-schedule:

    Node-schedule 的学习曲线较低,易于上手,适合大多数开发者。

社区支持

  • agenda:

    Agenda 拥有活跃的社区和良好的文档支持,适合需要社区帮助的开发者。

  • cron:

    Cron 是一个经典的库,社区支持广泛,但可能缺乏更新和活跃度。

  • later:

    Later 也有一定的社区支持,但相对较小,文档较为简洁。

  • node-schedule:

    Node-schedule 拥有良好的社区支持和文档,适合需要快速解决问题的开发者。

性能

  • agenda:

    Agenda 的性能依赖于 MongoDB 的性能,适合需要高可靠性的任务调度。

  • cron:

    Cron 的性能非常优秀,适合轻量级的定时任务,几乎没有性能开销。

  • later:

    Later 的性能在处理复杂调度时可能会受到影响,适合不频繁执行的任务。

  • node-schedule:

    Node-schedule 的性能良好,适合大多数常见的定时任务需求。

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

  • agenda:

    选择 Agenda 如果你需要一个基于 MongoDB 的任务调度库,适合需要持久化任务状态和调度的应用。它支持复杂的任务调度和重复任务,非常适合需要高可靠性的场景。

  • cron:

    选择 Cron 如果你熟悉 UNIX 的 cron 表达式,并且需要一个简单、轻量级的解决方案来定期执行任务。它适合简单的定时任务,不需要复杂的调度逻辑。

  • later:

    选择 Later 如果你需要一个灵活的调度库,支持多种时间格式和复杂的调度需求。它允许使用自然语言描述时间,适合需要高度自定义的调度场景。

  • node-schedule:

    选择 Node-schedule 如果你需要一个简单易用的定时任务库,支持 cron 表达式和 JavaScript 日期对象。它适合大多数常见的调度需求,易于上手。

agenda的README

Agenda

Agenda

A light-weight job scheduling library for Node.js

NPM Version NPM Downloads

Migrating from v5? See the Migration Guide for all breaking changes.

Agenda 6.x

Agenda 6.x is a complete TypeScript rewrite with a focus on modularity and flexibility:

  • Pluggable storage backends - Choose from MongoDB, PostgreSQL, Redis, or implement your own. Each backend is a separate package - install only what you need.

  • Pluggable notification channels - Move beyond polling with real-time job notifications via Redis, PostgreSQL LISTEN/NOTIFY, or other pub/sub systems. Jobs get processed immediately when saved, not on the next poll cycle.

  • Modern stack - ESM-only, Node.js 18+, full TypeScript with strict typing.

See the 6.x Roadmap for details and progress.

Features

  • Minimal overhead job scheduling
  • Pluggable storage backends (MongoDB, PostgreSQL, Redis)
  • TypeScript support with full typing
  • Scheduling via cron or human-readable syntax
  • Configurable concurrency and locking
  • Real-time job notifications (optional)
  • Sandboxed worker execution via fork mode
  • TypeScript decorators for class-based job definitions

Installation

Install the core package and your preferred backend:

# For MongoDB
npm install agenda @agendajs/mongo-backend

# For PostgreSQL
npm install agenda @agendajs/postgres-backend

# For Redis
npm install agenda @agendajs/redis-backend

Requirements:

  • Node.js 18+
  • Database of your choice (MongoDB 4+, PostgreSQL, or Redis)

Quick Start

import { Agenda } from 'agenda';
import { MongoBackend } from '@agendajs/mongo-backend';

const agenda = new Agenda({
  backend: new MongoBackend({ address: 'mongodb://localhost/agenda' })
});

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

// Start processing
await agenda.start();

// Schedule jobs
await agenda.every('1 hour', 'send email', { to: 'user@example.com', subject: 'Hello' });
await agenda.schedule('in 5 minutes', 'send email', { to: 'admin@example.com', subject: 'Report' });
await agenda.now('send email', { to: 'support@example.com', subject: 'Urgent' });

Official Backend Packages

PackageBackendNotificationsInstall
@agendajs/mongo-backendMongoDBPolling onlynpm install @agendajs/mongo-backend
@agendajs/postgres-backendPostgreSQLLISTEN/NOTIFYnpm install @agendajs/postgres-backend
@agendajs/redis-backendRedisPub/Subnpm install @agendajs/redis-backend

Backend Capabilities

BackendStorageNotificationsNotes
MongoDB (MongoBackend)Storage only. Combine with external notification channel for real-time.
PostgreSQL (PostgresBackend)Full backend. Uses LISTEN/NOTIFY for notifications.
Redis (RedisBackend)Full backend. Uses Pub/Sub for notifications.
InMemoryNotificationChannelNotifications only. For single-process/testing.

Backend Configuration

MongoDB

import { Agenda } from 'agenda';
import { MongoBackend } from '@agendajs/mongo-backend';

// Via connection string
const agenda = new Agenda({
  backend: new MongoBackend({ address: 'mongodb://localhost/agenda' })
});

// Via existing MongoDB connection
const agenda = new Agenda({
  backend: new MongoBackend({ mongo: existingDb })
});

// With options
const agenda = new Agenda({
  backend: new MongoBackend({
    mongo: db,
    collection: 'jobs'        // Collection name (default: 'agendaJobs')
  }),
  processEvery: '30 seconds', // Job polling interval
  maxConcurrency: 20,         // Max concurrent jobs
  defaultConcurrency: 5       // Default per job type
});

PostgreSQL

import { Agenda } from 'agenda';
import { PostgresBackend } from '@agendajs/postgres-backend';

const agenda = new Agenda({
  backend: new PostgresBackend({
    connectionString: 'postgresql://user:pass@localhost:5432/mydb'
  })
});

Redis

import { Agenda } from 'agenda';
import { RedisBackend } from '@agendajs/redis-backend';

const agenda = new Agenda({
  backend: new RedisBackend({
    connectionString: 'redis://localhost:6379'
  })
});

Real-Time Notifications

For faster job processing across distributed systems:

import { Agenda, InMemoryNotificationChannel } from 'agenda';
import { MongoBackend } from '@agendajs/mongo-backend';

const agenda = new Agenda({
  backend: new MongoBackend({ mongo: db }),
  notificationChannel: new InMemoryNotificationChannel()
});

Mixing Storage and Notification Backends

You can use MongoDB for storage while using a different system for real-time notifications:

import { Agenda } from 'agenda';
import { MongoBackend } from '@agendajs/mongo-backend';
import { RedisBackend } from '@agendajs/redis-backend';

// MongoDB for storage + Redis for real-time notifications
const redisBackend = new RedisBackend({ connectionString: 'redis://localhost:6379' });
const agenda = new Agenda({
  backend: new MongoBackend({ mongo: db }),
  notificationChannel: redisBackend.notificationChannel
});

This is useful when you want MongoDB's proven durability and flexible queries for job storage, but need faster real-time notifications across multiple processes.

API Overview

Defining Jobs

// Simple async handler
agenda.define('my-job', async (job) => {
  console.log('Processing:', job.attrs.data);
});

// With options
agenda.define('my-job', async (job) => { /* ... */ }, {
  concurrency: 10,
  lockLimit: 5,
  lockLifetime: 10 * 60 * 1000, // 10 minutes
  priority: 'high'
});

Defining Jobs with Decorators

For a class-based approach, use TypeScript decorators:

import { JobsController, Define, Every, registerJobs, Job } from 'agenda';

@JobsController({ namespace: 'email' })
class EmailJobs {
  @Define({ concurrency: 5 })
  async sendWelcome(job: Job<{ userId: string }>) {
    console.log('Sending welcome to:', job.attrs.data.userId);
  }

  @Every('1 hour')
  async cleanupBounced(job: Job) {
    console.log('Cleaning up bounced emails');
  }
}

registerJobs(agenda, [new EmailJobs()]);
await agenda.start();

// Schedule using namespaced name
await agenda.now('email.sendWelcome', { userId: '123' });

See Decorators Documentation for full details.

Scheduling Jobs

// Run immediately
await agenda.now('my-job', { userId: '123' });

// Run at specific time
await agenda.schedule('tomorrow at noon', 'my-job', data);
await agenda.schedule(new Date('2024-12-25'), 'my-job', data);

// Run repeatedly
await agenda.every('5 minutes', 'my-job');
await agenda.every('0 * * * *', 'my-job'); // Cron syntax

Job Control

// Cancel jobs matching a filter (removes from database)
await agenda.cancel({ name: 'my-job' });
await agenda.cancel({ name: 'my-job', data: { userId: 123 } });

// Cancel ALL jobs unconditionally
await agenda.cancelAll();

// Disable/enable jobs globally (by query)
await agenda.disable({ name: 'my-job' });  // Disable all jobs matching query
await agenda.enable({ name: 'my-job' });   // Enable all jobs matching query

// Disable/enable individual jobs
const job = await agenda.create('my-job', data);
job.disable();
await job.save();

// Progress tracking
agenda.define('long-job', async (job) => {
  for (let i = 0; i <= 100; i += 10) {
    await doWork();
    await job.touch(i); // Report progress 0-100
  }
});

Stopping / Draining

// Stop immediately - unlocks running jobs so other workers can pick them up
await agenda.stop();

// Drain - waits for running jobs to complete before stopping
await agenda.drain();

// Drain with timeout (30 seconds) - for cloud platforms with shutdown deadlines
const result = await agenda.drain(30000);
if (result.timedOut) {
    console.log(`${result.running} jobs still running after timeout`);
}

// Drain with AbortSignal - for external control
const controller = new AbortController();
setTimeout(() => controller.abort(), 30000);
await agenda.drain({ signal: controller.signal });

Use drain() for graceful shutdowns where you want in-progress jobs to finish their work.

Events

agenda.on('start', (job) => console.log('Job started:', job.attrs.name));
agenda.on('complete', (job) => console.log('Job completed:', job.attrs.name));
agenda.on('success', (job) => console.log('Job succeeded:', job.attrs.name));
agenda.on('fail', (err, job) => console.log('Job failed:', job.attrs.name, err));

// Job-specific events
agenda.on('start:send email', (job) => { /* ... */ });
agenda.on('fail:send email', (err, job) => { /* ... */ });

Use fail listeners to capture richer error context, such as stack traces, without storing large payloads in job.attrs.failReason:

agenda.on('fail', async (err, job) => {
	await saveJobError({
		jobId: job.attrs._id,
		jobName: job.attrs.name,
		message: err.message,
		stack: err.stack
	});
});

Custom Backend

For databases other than MongoDB, PostgreSQL, or Redis, implement AgendaBackend:

import { AgendaBackend, JobRepository } from 'agenda';

class SQLiteBackend implements AgendaBackend {
  readonly repository: JobRepository;
  readonly notificationChannel = undefined; // Or implement NotificationChannel

  async connect() { /* ... */ }
  async disconnect() { /* ... */ }
}

const agenda = new Agenda({
  backend: new SQLiteBackend({ path: './jobs.db' })
});

See Custom Backend Driver for details.

Documentation

Related Packages

Official Backend Packages:

Tools:

License

MIT