본문 바로가기

JavaScript/NestJS

[NestJS] 스케줄러로 반복 작업 설정하기

배경

웹 서비스를 만들 때 특정 시간에 특정 작업 반복이 필요한 경우가 있습니다. 예를 들어, 쇼핑몰을 만든다고 할 때 배송이 완료된 후 일정 시간 뒤 자동으로 구매 확정으로 상태를 변경해준다든지의 작업이 예입니다. NestJS에서는 이러한 반복적 배치 작업을 스케줄러로 구현할 수 있습니다. 또한 특정 이벤트가 발생했을 때 작업을 실행하게 해주는 커스텀 프로바이더라는 것도 존재합니다.

이 글에선 반복적 작업이 목적이기 때문에 스케줄러를 사용해서 구현하려고 합니다.

 


1. 패키지 설치

필요한 패키지를 설치합니다.

npm install --save @nestjs/schedule
npm install --save-dev @types/cron

 

2. app.module.ts

앱에 스케줄 모듈을 import 해줍니다.

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

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

 

3. Task 모듈, 서비스 생성

nest g module cron-task
nest g service cron-task

 

4. 서비스 구현 예시

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

@Injectable()
export class CronTaskService {
  constructor(@InjectDataSource() private readonly dataSource: DataSource) {}
  private readonly logger = new Logger(CronTaskService.name);

  @Cron('0 0 0 * * *')
  async batchLessonPrgsCd() {
    // 5일 이전 생성된 모든 데이터의 상태값 변경
    await this.dataSource.manager
      .createQueryBuilder()
      .update(Example)
      .set({ status: 'SOMETHING' })
      .where(`reg_date <= current_timestamp - interval '5 days'`)
      .execute();

    this.logger.debug('batch executed');
  }
}

 

위 구현 기준으로 매일 0시 0분마다 정의한 작업이 자동으로 실행됩니다.

 


참고

https://docs.nestjs.com/techniques/task-scheduling

https://computer-science-student.tistory.com/746

'JavaScript > NestJS' 카테고리의 다른 글

[NestJS] 채팅 구현하기(with ReactJS)  (1) 2023.05.22
GCS에 파일 업로드(NestJS)  (1) 2023.02.01