Nâng CaoNestJS iconNestJS

Scheduler và CRON jobs trong NestJS với @nestjs/schedule?

@nestjs/schedule wrapper của node-cron cho phép chạy tasks theo lịch:

typescript
import { Cron, CronExpression, Interval, Timeout } from '@nestjs/schedule';

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

  // Chạy lúc 12:00 AM mỗi ngày
  @Cron(CronExpression.EVERY_DAY_AT_MIDNIGHT)
  async generateDailyReport() {
    this.logger.log('Generating daily report...');
    await this.reportsService.generate();
  }

  // Chạy mỗi 30 giây
  @Interval(30000)
  async syncExternalData() { ... }

  // Chạy một lần sau 5 giây kể từ khi app start
  @Timeout(5000)
  async warmupCache() { ... }

  // Dynamic cron với SchedulerRegistry
  constructor(private schedulerRegistry: SchedulerRegistry) {}

  addCronJob(name: string, cronTime: string) {
    const job = new CronJob(cronTime, () => this.doWork());
    this.schedulerRegistry.addCronJob(name, job);
    job.start();
  }
}

Pitfall: trong distributed/multiple instances, cần distributed lock (Redis + Redlock) để tránh cùng job chạy parallel trên nhiều pods.

Xem toàn bộ NestJS cùng filter theo level & chủ đề con.

Mở danh sách NestJS