javascriptcronnestjsschedule

How to use nestjs schedule


I am using the schedule of nestjs to process the cron so that it works every specific time.

However, even though the cron that was first created for testing has been removed, it continues to go back every 0 o'clock.

the cron that was made for the test is not confirmed even if the entire contents are searched.

The following is the code I wrote.

// package.json

"dependencies": {
    "@nestjs/common": "^10.0.0",
    "@nestjs/config": "^3.1.1",
    "@nestjs/core": "^10.0.0",
    "@nestjs/jwt": "^10.2.0",
    "@nestjs/platform-express": "^10.0.0",
    "@nestjs/schedule": "^4.1.0",
    "@nestjs/swagger": "^7.2.0",
    "@nestjs/typeorm": "^10.0.1",
    "body-parser": "^1.20.2",
    "class-transformer": "^0.5.1",
    "class-validator": "^0.14.1",
    "jsonwebtoken": "^9.0.2",
    "mime-types": "^2.1.35",
    "moment-timezone": "^0.5.44",
    "reflect-metadata": "^0.1.13",
    "rxjs": "^7.8.1",
    "typeorm": "^0.3.19",
    "typeorm-extension": "^3.4.0",
    "yarn": "^1.22.21"
  },
// app.module.ts

import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import ConfigModule from './config';
import { LoggingMiddleware } from './common/middleware/logging.middleware';
import { ScheduleModule } from '@nestjs/schedule';
import { BatchService } from './batch.service';

@Module({
  imports: [
    ConfigModule(),
    ScheduleModule.forRoot(),
  ],
  providers: [BatchService],
})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(LoggingMiddleware).forRoutes('*');
  }
}

Test batch.service.ts was used and deleted only when testing.

// TEST batch.service.ts
 
import { Injectable, Logger } from '@nestjs/common';
import { Cron, CronExpression, SchedulerRegistry } from '@nestjs/schedule';
import { EventService } from './routes/client/event/event.service';

@Injectable()
export class BatchService {
  constructor(
    private readonly eventService: EventService,
    private schedulerRegistry: SchedulerRegistry
  ) {}

  @Cron(CronExpression.EVERY_DAY_AT_MIDNIGHT)
  async handleAttendanceEvents() {
    await this.eventService.checkAttendanceByCron();
  }
}

The file below is the actual contents of your current operation.

// REAL batch.service.ts

import { Injectable, Logger } from '@nestjs/common';
import { Cron, CronExpression, SchedulerRegistry } from '@nestjs/schedule';
import { EventService } from './routes/client/event/event.service';

@Injectable()
export class BatchService {
  constructor(
    private readonly eventService: EventService,
  ) {}

  @Cron(CronExpression.EVERY_DAY_AT_MIDNIGHT, {
    name: 'attendance',
  })
  async handleAttendanceEvents() {
    await this.eventService.checkAttendanceByCron();
  }
}

When viewed from getCronJobs, the following logs are displayed.

[Nest] 646445  - 05/11/2025, 00:00:00 PM LOG job: attendance -> next: Mon May 12 2025 00:00:00

From above, like the relevant log content, only one is searched and two are not. However, in reality, two are running. Seeking help on how to delete previously incorrectly written cron.


Solution

  • You can use the following in the BatchService - this will delete the previous cron jobs and start the new one on restart server:

     async onModuleInit() {
        const jobs: any = this.schedulerRegistry.getCronJobs();
        jobs.forEach((value, key, map) => {
          this.schedulerRegistry.deleteCronJob(key);
        });
      }