node cron

Younghwan Cha·2022년 10월 20일
0
post-thumbnail

일정한 시간에 주기적으로 어떤 로직을 실행하려면 어떻게 해야할까? 이 질문에 cron 이 답이 될 수 있을 것 같다.

node-cron 과 cron 두가지가 있는데 이 둘은 비슷한 기능을 하는 것으로 보이지만 분명 다른 두 모듈이기 때문에 사용할 때 참고하도록 하자.

npm install --save cron

아래와 같이 간단하게 실행이 가능하다.

import { CronJob } from 'cron'.CronJob;

const job = new Cronjob('* * * * *', () => {
  console.log('running a task every minute');
});

Cron 실행 주기

상단에 * 표시된 곳에는 각각에 해당되는 날짜를 적어주면 된다.
cron 모듈마다 구현되는 방식이 다르기 때문에 ( 예를들어, 다른 모듈의 경우 0-7 를 month range 로 사용하며 0 과 7 두개를 Sunday 로 사용하기도 한다 ) 알맞는 기간을 정해 사용한는 것이 중요하다.

  • Seconds: 0-59( optional )
  • Minutes: 0-59
  • Hours: 0-23
  • Day of Month: 1-31
  • Months: 0-11 (Jan-Dec)
  • Day of Week: 0-6 (Sun-Sat)
import { CronJob } from 'cron'.CronJob;

// 아래와 같이 작성할 경우 09시 매 분 마다 로직이 실행되게 된다
const job = new Cronjob('* * 9 * *', () => {
  console.log('running a task every minute');
});

// 매일 09시에 실행하려면 다음과 같이 작성해야 한다
const job = new Cronjob('0 9 * * *', () => {
  console.log('running a task every minute');
});

// 10분에 로직이 실행
const job = new Cronjob('10 * * * *', () => {
  console.log('running a task every minute');
});

// 10분 마다 로직이 실행
const job = new Cronjob('*/10 * * * *', () => {
  console.log('running a task every minute');
});

API

가장 중요한 CronJob 만 한번 살펴보자.

  • CronJob
    • constructor(cronTime, onTick, onComplete, start, timezone, context, runOnInit, utcOffset, unrefTimeout)
      • cronTime - [REQUIRED] - The time to fire off your job. This can be in the form of cron syntax or a JS Date object.
      • onTick - [REQUIRED] - The function to fire at the specified time. If an onComplete callback was provided, onTick will receive it as an argument. onTick may call onComplete when it has finished its work.
      • onComplete - [OPTIONAL] - A function that will fire when the job is stopped with job.stop(), and may also be called by onTick at the end of each run.
      • start - [OPTIONAL] - Specifies whether to start the job just before exiting the constructor. By default this is set to false. If left at default you will need to call job.start() in order to start the job (assuming job is the variable you set the cronjob to). This does not immediately fire your onTick function, it just gives you more control over the behavior of your jobs.
      • timeZone - [OPTIONAL] - Specify the timezone for the execution. This will modify the actual time relative to your timezone. If the timezone is invalid, an error is thrown. You can check all timezones available at Moment Timezone Website. Probably don't use both timeZone and utcOffset together or weird things may happen.
      • context - [OPTIONAL] - The context within which to execute the onTick method. This defaults to the cronjob itself allowing you to call this.stop(). However, if you change this you'll have access to the functions and values within your context object.
      • runOnInit - [OPTIONAL] - This will immediately fire your onTick function as soon as the requisite initialization has happened. This option is set to false by default for backwards compatibility.
      • utcOffset - [OPTIONAL] - This allows you to specify the offset of your timezone rather than using the timeZone param. Probably don't use both timeZone and utcOffset together or weird things may happen.
      • unrefTimeout - [OPTIONAL] - If you have code that keeps the event loop running and want to stop the node process when that finishes regardless of the state of your cronjob, you can do so making use of this parameter. This is off by default and cron will run as if it needs to control the event loop. For more information take a look at timers#timers_timeout_unref from the NodeJS docs.

[ref]

https://crontab.guru/#*_*_*_*_*

https://www.npmjs.com/package/cron
https://www.npmjs.com/package/node-cron

profile
개발 기록

0개의 댓글