agenda、bree、bull、cron、later、node-cron、node-schedule は、Node.js アプリケーション内で時間ベースのタスク実行やバックグラウンドジョブ処理を実現するためのライブラリ群です。これらは大きく分けて 2 つのカテゴリに分類されます。一つは、Cron 構文や自然言語に基づいて特定の日時にコードを実行する「スケジューラ」(node-cron、node-schedule、cron、later)であり、もう一つは、Redis や MongoDB などの外部ストレージを利用してジョブの永続化、再試行、優先度管理を行う「ジョブキュー」(bull、agenda、bree)です。フロントエンドアーキテクチャの観点からは、サーバーサイドレンダリング(SSR)中のデータ取得、定期的なキャッシュ更新、あるいは長時間実行される重い処理の非同期オフロードといったシナリオにおいて、適切なツールを選定することがシステムの信頼性と拡張性に直結します。
Node.js アプリケーションにおいて、時間の経過とともにタスクを実行する必要性は頻繁に発生します。例えば、毎日のレポート生成、キャッシュの更新、あるいはユーザーへのメール送信などです。ここで紹介する 7 つのパッケージ(agenda, bree, bull, cron, later, node-cron, node-schedule)は、この課題を解決するための代表的なツールですが、そのアプローチは大きく 2 つに分かれます。
一つは「スケジューラ」であり、特定の時刻になったらコードを実行するものです。もう一つは「ジョブキュー」であり、タスクをキューに詰め込み、ワーカーが順番に処理していくものです。どちらを選ぶかは、データの永続性が必要か、処理の規模はどれくらいか、そしてインフラに何を導入できるかによって決まります。
まず理解すべきは、これらのツールが「状態(State)」をどこで管理しているかという点です。
スケジューラ系(node-cron, node-schedule, cron, later)は、基本的にメモリ上で動作します。プロセスが再起動すると、設定したスケジュールは消滅します。これらは「その瞬間」を実行することに特化しており、ジョブの履歴や失敗時の再試行ロジックは自分で実装する必要があります。
ジョブキュー系(bull, agenda, bree)は、外部ストレージ(Redis, MongoDB, ファイルシステム)にジョブの状態を保存します。プロセスが落ちてもジョブは消えず、再起動後に再開できます。また、複数のサーバーで同じキューを共有することで、負荷分散も可能です。
定期実行タスクを実装する際、構文の書きやすさと機能性が重要です。ここでは、node-cron、node-schedule、および非推奨の cron、later を比較します。
node-cron は、標準的な Cron 構文をサポートし、API がシンプルで現代的なプロジェクトでよく使われます。
const cron = require('node-cron');
// 毎分実行
const task = cron.schedule('* * * * *', () => {
console.log('毎分実行されます');
});
// 一時停止や再開も容易
task.stop();
task.start();
cron パッケージも同様の構文を使いますが、メンテナンス状況が不安定なため、新規採用は推奨されません。API は似ていますが、生態系のサポートが薄れています。
const CronJob = require('cron').CronJob;
// 毎分実行
const job = new CronJob('* * * * *', function() {
console.log('毎分実行されます');
});
job.start();
node-schedule は、Cron 構文に加え、より人間に優しいルールや Date オブジェクトを直接指定できる柔軟性があります。
const schedule = require('node-schedule');
// Cron 構文での指定
const job1 = schedule.scheduleJob('* * * * *', function() {
console.log('毎分実行されます');
});
// 自然言語的なルール(毎週月曜日の 12:30)
const job2 = schedule.scheduleJob('DayOfWeek Hour:Minute', function() {
console.log('月曜日の 12:30 に実行');
});
// 特定の時刻(Date オブジェクト)に 1 回だけ実行
const date = new Date(Date.now() + 5000);
const job3 = schedule.scheduleJob(date, function() {
console.log('5 秒後に 1 回実行');
});
later は、非常に複雑なスケジュール(例:「月の最初の平日の午前 9 時」など)を記述できる強力な構文を持っていましたが、現在はメンテナンスされていません。新規プロジェクトで使用すべきではありません。
// later の例(非推奨のため参考のみ)
const later = require('later');
const schedule = later.parse.text('every weekday at 9:00 am');
later.setInterval(() => {
console.log('複雑なスケジュール実行');
}, schedule);
選定のポイント:
シンプルな定期実行なら node-cron が十分です。もし「特定の日のみ」や「動的な日付」を扱う必要があるなら、node-schedule の方が直感的でバグを埋め込みにくくなります。cron や later は、既存レガシーコードの維持以外では選択しないようにしましょう。
バックグラウンドで重い処理(画像リサイズ、メール送信、外部 API 連携など)を行う場合、ジョブキューが必須です。ここでは bull、agenda、bree を比較します。
bullbull は Redis をバックエンドに使用し、非常に高速で信頼性が高いのが特徴です。ジョブの優先度、再試行、進行状況の報告など、エンタープライズ級の機能が揃っています。
const Queue = require('bull');
// キューの作成(Redis 接続が必要)
const imageQueue = new Queue('image processing', 'redis://127.0.0.1:6379');
// ジョブの追加
imageQueue.add({ imageUrl: 'https://example.com/img.png' }, {
attempts: 3, // 失敗時 3 回再試行
backoff: { type: 'exponential', delay: 1000 }
});
// ワーカーの実装
imageQueue.process(async (job) => {
console.log(`処理中: ${job.data.imageUrl}`);
// 画像リサイズ処理など
job.progress(50); // 進捗報告
return { success: true };
});
agendaagenda は MongoDB を使用します。ジョブの定義をデータベースに保存できるため、アプリケーションコードを変更せずに DB 上でジョブを管理できる利点があります。
const Agenda = require('agenda');
const agenda = new Agenda({ db: { address: 'mongodb://localhost/agenda' } });
// ジョブの定義
agenda.define('send email', async (job) => {
const { to, subject } = job.attrs.data;
console.log(`${to} に ${subject} を送信`);
});
// ジョブのスケジューリング
await agenda.start();
await agenda.every('10 minutes', 'send email', { to: '[email protected]', subject: '定期メール' });
// 一度きりのジョブ
await agenda.schedule('in 20 minutes', 'send email', { to: '[email protected]', subject: '警告' });
breebree は、Redis や MongoDB を必要とせず、ファイルシステム上でジョブを管理します。ワーカーを別プロセスとして起動するため、メモリリークの影響を受けにくい設計になっています。
const Bree = require('bree');
const path = require('path');
const bree = new Bree({
root: path.join(__dirname, 'jobs'), // ジョブスクリプトが入ったフォルダ
jobs: [
{ name: 'daily-report', interval: 'at 12:00 am' },
{ name: 'process-images', path: path.join(__dirname, 'workers', 'image-worker.js') }
]
});
bree.start();
// ジョブスクリプト (jobs/daily-report.js)
// module.exports = async () => { console.log('レポート生成'); };
選定のポイント:
Redis を導入できる環境で、高いパフォーマンスと機能性を求めるなら bull がベストです。既に MongoDB を使っており、ジョブ定義を DB で管理したい場合は agenda が適しています。インフラを増やしたくない、あるいはワーカーのプロセス分離を簡単に実現したい場合は bree が優れた選択肢です。
ジョブが失敗した時の挙動も重要な選定基準です。
bull: 組み込みの再試行機能が強力です。attempts オプションで再試行回数を指定でき、バックオフ戦略(再試行までの待機時間を徐々に増やすなど)も設定可能です。ジョブは Redis に残るため、サーバーが落ちても復旧後に再開されます。agenda: MongoDB にジョブ状態が保存されるため、プロセス停止後もジョブは失われません。ただし、ロック機構を使用しているため、長時間実行されるジョブがデッドロックを起こさないよう注意が必要です。bree: ワーカープロセスがクラッシュしても、メインプロセスがそれを検知し、必要に応じて再起動できます。設定により、失敗したジョブの再試行も可能です。node-cron など): 基本的にエラーハンドリングはユーザー任せです。try-catch で囲まないとプロセスが終了する可能性があり、再試行ロジックも自分で実装する必要があります。また、プロセス再起動でスケジュールがリセットされるため、重要なタスクには不向きです。各パッケージがどのように「10 分後に実行」というタスクを扱うかを見てみましょう。
// node-schedule (スケジューラ)
const date = new Date(Date.now() + 10 * 60 * 1000);
schedule.scheduleJob(date, () => console.log('10 分後'));
// node-cron (スケジューラ - 厳密な 10 分後は難しいため近似)
// 毎分チェックして条件分岐するか、setTimeout を併用する必要がある
setTimeout(() => console.log('10 分後'), 10 * 60 * 1000);
// bull (キュー - 遅延実行)
queue.add({ type: 'task' }, { delay: 10 * 60 * 1000 });
// agenda (キュー/スケジューラハイブリッド)
agenda.schedule('in 10 minutes', 'myTask');
// bree (スケジューラ設定)
// jobs 配列で interval: 'in 10 minutes' と指定
フロントエンドアーキテクチャの文脈では、サーバーサイドレンダリング(SSR)中のデータ取得にこれらのツールを使うことは稀ですが、SSR のキャッシュ戦略や、ユーザーアクションに対する非同期フィードバック(例:「エクスポート準備ができたらメールします」)において重要な役割を果たします。
node-cron または bree がおすすめです。特に bree はプロセス分離のメリットが大きく、安定性が高いです。bull を選ぶべきです。その機能性は開発中の悩みを大きく減らしてくれます。agenda が自然な選択です。cron と later はメンテナンスの観点から、新規プロジェクトでは使用を避けてください。node-cron や node-schedule で十分な代替が可能です。どのツールを選ぶにしても、「プロセスが落ちたらジョブはどうなるか?」という問いに答えられる構成にすることが、プロフェッショナルなシステム設計の第一歩です。
純粋な Cron 構文のパーサーとして機能し、特定の時刻にコールバックを実行するだけのシンプルな用途に限定して使用します。ジョブの永続化や管理機能は含まれていないため、プロセスが再起動するとスケジュールがリセットされる点に注意が必要です。現代的なプロジェクトでは、よりメンテナンスが活発で機能豊富な node-cron や node-schedule の使用を検討すべきであり、新規プロジェクトでの採用は推奨されません。
Cron 構文だけでなく、特定の Date オブジェクトや自然言語的なルール(例:『毎週月曜日の午前 9 時』)でスケジュールを定義したい場合に node-schedule を選択します。可読性の高いスケジュール定義が可能で、ジョブのキャンセルや再スケジュールも容易です。データベースを必要としない範囲で、柔軟かつ直感的な時刻指定が必要なアプリケーションに適しています。
MongoDB を既にインフラとして利用しており、ジョブの定義をコード内ではなくデータベース上で動的に管理したい場合に agenda を選択します。ジョブの実行履歴や状態を DB で永続化できるため、プロセスが再起動してもジョブが失われません。ただし、MongoDB への依存と、ロック機構によるパフォーマンスの限界があるため、超高速な処理や Redis 環境では他の選択肢を検討すべきです。
ファイルシステムに基づいてジョブを管理し、外部データベース(Redis や MongoDB)を一切必要としない軽量な構成を求める場合に bree が最適です。ワーカープロセスを分離して実行するため、メモリのリークがメインプロセスに影響しにくい利点があります。小規模から中規模のプロジェクトで、インフラの複雑さを増やさずに堅牢なバックグラウンド処理を実装したい時に推奨されます。
Redis を利用可能で、高いスループット、ジョブの優先度制御、詳細なイベント処理、そして分散環境での信頼性を求める場合には bull が事実上の標準です。ジョブの進行状況の監視や失敗時の再試行戦略を細かく制御できるため、大規模なバックグラウンド処理システムに適しています。Redis のメンテナンスコストを受け入れられるなら、最も機能豊富で信頼性の高い選択肢です。
自然言語に近い形式や複雑なスケジュール構文で時刻を定義する必要がある場合に使用しますが、このパッケージは現在メンテナンスが終了しており、新規プロジェクトでの使用は避けるべきです。機能面では柔軟性がありますが、セキュリティアップデートやバグ修正が見込めないため、代替として node-schedule や croner などの維持されているライブラリへの移行を強く推奨します。
外部依存なしで Cron 構文に基づいてタスクをスケジュールしたい場合の、バランスの取れた選択肢です。cron パッケージよりもメンテナンスが活発で、Node.js の最新の機能にも対応しています。ジョブの永続化機能はありませんが、シンプルな定期実行タスク(例:毎日のバッチ処理)をステートレスに実行したい場合に適しており、導入コストが低いのが特徴です。
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!
child_processnpm install cron
v4 dropped Node v16 and renamed the job.running property:
Node v16 is no longer supported. Upgrade your Node installation to Node v18 or above
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:
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.
CronJobCronJob.from(argsObject) instead.nextDates(count?: number) now always returns an array (empty if no argument is provided). Use nextDate() instead for a single date.removed job() method in favor of new CronJob(...args) / CronJob.from(argsObject)
removed time() method in favor of new CronTime()
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 usingjob.start().
For more advanced examples, check the examples directory.
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.
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".
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}`);
}
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.
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.
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
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.
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).
Join the Discord server! Here you can discuss issues and get help in a more casual forum than GitHub.
This project is looking for help! If you're interested in helping with the project, please take a look at our contributing documentation.
Please have a look at our contributing documentation, it contains all the information you need to know before submitting an issue.
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.
MIT