cronnestjsscheduled-tasks

CRON job executing twice at scheduled time (NestJS)


I want to execute this cron function in my NestJs project :

@Cron('59 23 * * *')
async CashPendingCRON(){
    let stores = await this.storeRepository.find();
    for (let store of stores){
        await this.connection
        .createQueryBuilder()
        .insert()
        .into(CashPending)
        .values([
        { cashPending: store.cashPending, store: store }
        ])
        .execute()
 }

As you can see the corn job is supposed to execute at 11:59 pm everyday. But it gets executed twice and the entries are logged in the DB two times. When I use intervals like 10 seconds (*/10 * * * * *) it gets called only once.

Please let me know if there is a fix or if I am doing something wrong.

Here is how I added the ScheduleModule in the app.module.ts

@Module({
  imports: [
    ScheduleModule.forRoot(),
    ConfigModule.forRoot({
      load: [appConfig, devConfig, stagConfig],
      ignoreEnvFile: true,
      isGlobal: true,
    }),
    TypeOrmModule.forRoot(
      configService.getTypeOrmConfig(),
    ),
    TypeOrmModule.forFeature([
      User,
      Vendor,
      Store,
      Product,
      Category,
      Brand,
      AppVersion
    ]),
    JwtModule.registerAsync({
      imports: [ConfigModule],
      useFactory: async () => ({
        secret: process.env.TOKEN_KEY,
      }),
      inject: [ConfigService],
    }),
    UserModule,
    UserClusterModule,
    StoreModule,
    OperationManagerModule,
    UserBrandModule,
    UserCatalogueModule,
    UserPropertyModule,
    FileModule,
    BrandModule,
    CategoryModule,
    ProductsModule,
    WarehouseModule,
    SubCategoryModule,
    StoreStocksModule,
    WarehouseStockModule,
    RtvStocksModule,
    VendorModule,
    CustomerModule,
    W2sModule,
    S2sModule,
    W2wModule,
    BillerModule,
    WarehouseManagerModule,
    AuthModule,
    OrderModule,
    GRNModule,
    SKUTimelinesModule,
    BannerModule,
    OrderReturnModule,
    UtilModule,
    POModule,
    AppVersion,
    S2wModule,
    CashOutModule
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

Please help. Thank you.


Solution

  • I was going through the same issue and the problem was that I was using the imports: [ScheduleModule.forRoot()] in a module that was imported twice (by other two modules). I solved it by creating a new module that is not imported by any other module and adding the ScheduleModule.forRoot() in it.

    scheduler.module.ts

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

    scheduler.service.ts

    import { Injectable } from '@nestjs/common';
    import { Cron, CronExpression } from '@nestjs/schedule';
    
    @Injectable()
    export class SchedulerService {
      @Cron(CronExpression.EVERY_10_SECONDS)
      handleExpiration() {
        console.log(new Date());
      }
    }
    

    Console output:

    2022-12-21T14:04:00.005Z
    2022-12-21T14:04:10.004Z
    2022-12-21T14:04:20.009Z
    2022-12-21T14:04:30.004Z
    2022-12-21T14:04:40.011Z
    ...