Frontend/Nest.js

Task Scheduling

wam 2024. 8. 26. 20:34

 

NestJS의 Task Scheduling

  • 원하는 time interval, 또는 정해진 시간과 날짜에 fuction을 실행할 수 있다.
  • 고정된 날짜/시간, 반복 간격 또는 지정된 간격마다 특정 메서드나 함수를 한 번 실행되도록 예약할 수 있다.

 

 

NestJS 문서

Task Scheduling

Task scheduling allows you to schedule arbitrary code (methods/functions) to execute at a fixed date/time, at recurring intervals, or once after a specified interval. In the Linux world, this is often handled by packages like cron at the OS level. For Node.js apps, there are several packages that emulate cron-like functionality. Nest provides the @nestjs/schedule package, which integrates with the popular Node.js cron package. We'll cover this package in the current chapter.

  • @nestjs/schedule는 node-cron이라는 패키지 위에서 나온다.
  • nestJs가 만든 것이 아닌 nestJs의 방식을 따르는 것이다.
  • Node.js의 경우 cron과 유사한 기능을 애뮬레이트하는 여러 패키지가 있는데, Nest는 인기 있는 Node.js node-cron 패키지와 통합되는 @nestjs/schedule 패키지를 제공한다.

 

 

설치

$ npm install --save @nestjs/schedule

 

 

사용법

 

 

앱모듈에 설정

app.module.ts

import { Module } from '@nestjs/common';
import { ScheduleModule } from '@nestjs/schedule';

@Module({
  imports: [
    ScheduleModule.forRoot()
  ],
})
export class AppModule {}

 

 

서비스 안에 cron 데코레이터 작성

import { Injectable, Logger } from '@nestjs/common';
import { Cron } from '@nestjs/schedule';

@Injectable()
export class TasksService {
  private readonly logger = new Logger(TasksService.name);

  @Cron('45 * * * * *')
  handleCron() {
    this.logger.debug('Called when the current second is 45');
  }
}
  • @Cron('45 * * * * *')
    • ('45 * * * * *') - cron pattern와 함께 call
    • 매 분 45초에 function이 실행

 

 

cron pattern

  • Asterisk (e.g. *)
      • 별표시는 “매” 즉 “모든” 것을 포함한 의미 이다.
  • Ranges (e.g. 1-3,5)
    • Range는 1-3 또는 1과 5를 의미
  • Steps (e.g. */2)
    • 2씩 간격을 의미

 

 

Cron 패턴(순서)

* * * * * *
| | | | | |
| | | | | day of week
| | | | months
| | | day of month
| | hours
| minutes
seconds (optional)
  • 초, 분, 시, 일, 월, 요일
  • 초는 생략 가능

 

 

cron pattern 예시

45 * * * * * 매 분 45초에 실행
0 10 * * * * 매 시 10분에 실행
0 */30 9-17 * * * 30분 마다 실행, 9 ~ 17시 사이의 30분마다 실행
0 30 11 * * 1-5 30분 마다 11시에 매일 매월 월(1)~금(5)에 실행
  • 45 * * * * *
    • 매 요일, 매 월, 매 일자, 매 시, 매 분 45초에 실행되는 것
    • 즉 매 분 45초에 실행은 매 분마다 초침이 45초에 가리킬 때 실행 되는 것
  • 1 요일 - 월요일, 5 요일 - 금요일을 의미

 

 

expression도 사용이 가능

import { Injectable, Logger } from '@nestjs/common';
import { Cron, CronExpression } from '@nestjs/schedule';

@Injectable()
export class TasksService {
  private readonly logger = new Logger(TasksService.name);

  @Cron(CronExpression.EVERY_30_SECONDS)
  handleCron() {
    this.logger.debug('Called every 30 seconds');
  }
}
  • 매 30초마다

 

 

Cron 테스트 - 매 분 10초마다 실행

import { Cron } from "@nestjs/schedule";

@Cron("10 * * * * *")
checkCron() {
  console.log("📢 Checking...");
}
  • 매 분 10초에 실행되는 것!
  • 초침이 10을 가리킬 때 실행 되는 것이다.

 

 

Declarative intervals

  • 메서드가 (반복적으로) 지정된 간격으로 실행되어야 한다고 선언하려면 메서드 정의에 @Interval() 데코레이터를 접두어로 붙인다.
  • 간격 값을 밀리초 단위의 숫자로 데코레이터에 전달한다.
  • 자바스크립트의 interval과 비슷하다.

 

 

intervals 테스트 - 10초마다 실행

import { Interval } from "@nestjs/schedule";

@Interval(10000)
checkInterval() {
  console.log("📢 checking...");
}
  • 10초마다 실행된다.

 

 

Declarative timeouts

  • 메서드가 지정된 시간에 한 번 실행되어야 한다고 선언하려면 메서드 정의 앞에 @Timeout() 데코레이터를 붙인다.
  • 오프셋(밀리 초)을 전달한다.
  • timeOut은 interval이랑 비슷하며 timeOut은 나중에 발생한다.
  • 애플리케이션이 시작되면 바로 timeOut이 실행된다.

 

 

timeouts 테스트 - 한 번 실행

@Timeout(10000)
checkTimeout() {
  console.log("📢 checking...");
}

 

 

Dynamic cron jobs

  • SchedulerRegistry API를 사용하여 코드의 어느 곳에서나 name으로 CronJob 인스턴스에 대한 참조를 가져온다.
  • 먼저 표준 constructor injection을 사용하여 SchedulerRegistry를 주입해야 한다.

 

 

SchedulerRegistry를 주입

constructor(private schedulerRegistry: SchedulerRegistry) {}

 

 

Cron을 Stop 하기

@Cron('* * 8 * * *', {
  name: 'notifications',
})

triggerNotifications() {
	const job = this.schedulerRegistry.getCronJob('notifications');

	job.stop();
	console.log(job.lastDate());
}
  • Cron의 name을 불러 실행을 멈출 수 있다.
  • job.lastDate() 메서드는 크론 작업이 마지막으로 실행된 날짜와 시간을 반환한다.

 

 

CronJob 메서드 종류

  • stop() - stops a job that is scheduled to run.
  • start() - restarts a job that has been stopped.
  • setTime(time: CronTime) - stops a job, sets a new time for it, and then starts it
  • lastDate() - returns a DateTime representation of the date on which the last execution of a job occurred.
  • nextDate() - returns a DateTime representation of the date when the next execution of a job is scheduled.
  • nextDates(count: number) - Provides an array (size count) of DateTime representations for the next set of dates that will trigger job execution. count defaults to 0, returning an empty array.