node-schedule vs bull vs agenda
Node.js 작업 스케줄러
node-schedulebullagenda類似パッケージ:

Node.js 작업 스케줄러

Node.js 작업 스케줄러는 백그라운드 작업을 예약하고 관리하는 데 사용되는 라이브러리입니다. 이러한 라이브러리는 주기적인 작업, 지연된 작업 및 특정 시간에 실행되는 작업을 설정할 수 있도록 도와줍니다. 이들은 서버 측에서 비동기 작업을 효율적으로 처리하고, 애플리케이션의 성능을 최적화하는 데 기여합니다.

npmのダウンロードトレンド

3 年

GitHub Starsランキング

統計詳細

パッケージ
ダウンロード数
Stars
サイズ
Issues
公開日時
ライセンス
node-schedule4,788,0159,19735.3 kB17311日前MIT
bull2,133,19616,262309 kB1472年前MIT
agenda212,2759,714310 kB195日前MIT

機能比較: node-schedule vs bull vs agenda

작업 저장 방식

  • node-schedule:

    Node-schedule은 메모리 기반으로 작업을 저장합니다. 따라서 간단한 작업을 빠르게 설정할 수 있지만, 서버가 재시작되면 작업 정보가 사라지는 단점이 있습니다.

  • bull:

    Bull은 Redis를 사용하여 작업을 큐에 저장합니다. Redis의 빠른 성능 덕분에 대량의 작업을 효율적으로 처리할 수 있으며, 작업의 우선순위를 설정할 수 있는 기능도 제공합니다.

  • agenda:

    Agenda는 MongoDB를 사용하여 작업을 저장합니다. 이를 통해 작업의 상태를 쉽게 관리하고, 작업이 실패했을 때 재시도하는 등의 기능을 구현할 수 있습니다.

성능 및 확장성

  • node-schedule:

    Node-schedule은 간단한 작업 스케줄링에 적합하지만, 대규모 작업 처리에는 한계가 있습니다. 복잡한 작업이 필요할 경우 다른 라이브러리를 고려해야 합니다.

  • bull:

    Bull은 Redis의 비동기 처리 능력을 활용하여 높은 성능을 자랑합니다. 대량의 작업을 신속하게 처리할 수 있으며, 클러스터링을 통해 확장성을 높일 수 있습니다.

  • agenda:

    Agenda는 MongoDB의 성능에 의존하므로, 데이터베이스의 성능이 작업 처리 속도에 영향을 미칩니다. 대규모 작업 처리에는 적합하지 않을 수 있습니다.

사용 용이성

  • node-schedule:

    Node-schedule은 설치와 설정이 간단하여, 빠르게 사용할 수 있습니다. 복잡한 설정 없이 주기적인 작업을 쉽게 설정할 수 있습니다.

  • bull:

    Bull은 Redis를 설정해야 하며, 큐 관리에 대한 이해가 필요합니다. 그러나 강력한 기능을 제공하므로 학습할 가치가 있습니다.

  • agenda:

    Agenda는 MongoDB와의 통합이 필요하므로, 데이터베이스 설정이 필요합니다. 그러나 API가 직관적이어서 사용하기 쉽습니다.

스케줄링 방식

  • node-schedule:

    Node-schedule은 cron 스타일의 스케줄링을 지원하여, 간단한 주기적 작업을 설정하는 데 적합합니다. 사용자가 쉽게 이해할 수 있는 형식으로 작업을 설정할 수 있습니다.

  • bull:

    Bull은 작업의 우선순위와 재시도 로직을 설정할 수 있어, 복잡한 작업 큐를 관리하는 데 유용합니다. 또한, 작업의 성공 및 실패를 추적할 수 있습니다.

  • agenda:

    Agenda는 다양한 스케줄링 옵션을 제공하며, 복잡한 작업 흐름을 설정할 수 있습니다. 특정 시간, 주기적인 작업 등을 유연하게 설정할 수 있습니다.

커뮤니티 및 지원

  • node-schedule:

    Node-schedule은 간단한 라이브러리이지만, 커뮤니티의 지원이 제한적일 수 있습니다. 그러나 기본적인 사용법은 문서화되어 있습니다.

  • bull:

    Bull은 활발한 커뮤니티와 많은 사용자를 보유하고 있으며, 다양한 예제와 문서가 제공되어 있어 지원이 잘 이루어집니다.

  • agenda:

    Agenda는 비교적 작은 커뮤니티를 가지고 있지만, 문서화가 잘 되어 있어 사용자가 쉽게 접근할 수 있습니다.

選び方: node-schedule vs bull vs agenda

  • node-schedule:

    Node-schedule은 간단한 작업 스케줄링을 제공하며, cron 스타일의 스케줄링을 지원합니다. 복잡한 설정 없이 간단한 주기적 작업이 필요할 때 적합합니다.

  • bull:

    Bull은 Redis를 사용하여 작업을 큐잉하는 라이브러리로, 높은 성능과 확장성을 제공합니다. 대규모 작업 처리 및 복잡한 큐 관리가 필요할 때 선택하는 것이 좋습니다.

  • agenda:

    Agenda는 MongoDB를 백엔드로 사용하는 작업 스케줄러로, 데이터베이스에 작업을 저장하고 관리할 수 있습니다. 데이터베이스 기반의 작업 관리가 필요할 때 적합합니다.

node-schedule のREADME

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.