#My cron runs 3 times in a row in a single instance

7 messages · Page 1 of 1 (latest)

sharp mantle
#

Hi guys, what's up? Why do you think it can happen that a CRON task runs 3 times in a row for no reason?

My code looks like this:

@Cron(CronExpression.EVERY_10_SECONDS)
async cronExample() {
  console.log('Hello world');
}

And my logs look like this:

#

And no, 3 seconds have not passed in that application execution, the 3 "Hello world" are displayed in a row.

mint merlin
#

you might have registered the service associated with the @Cron() multiple times as a provider

quaint yachtBOT
#

Don't list a service in providers array of a module unless the module really provides the service.
If your ServiceA depends on a ServiceB from different module ModuleB, add ServiceB to ModuleBs exports array,
then add ModuleB to imports array in your module.

@Module({
  providers: [ServiceB],
  exports: [
    ServiceB // <-- export the "ServiceB" provider by adding it to the module's exports array
  ], 
})
export class ModuleB {}
@Module({
  imports: [
    ModuleB // <-- modules that wish to inject the "ServiceB" will need to import the "ModuleB" in their imports array
  ],  
  providers: [ServiceA],
})
export class ModuleA {}
import { ServiceB } from '../module-b/service-b.service'

@Injectable()
export class ServiceA {
  constructor(private readonly serviceB: ServiceB) {}
  
  // async foo() {
  //   this.serviceB.bar();
  // }
}
sharp mantle
#

Oh, yes it is precisely that, what do you recommend me, separate the cron tasks in another module, or what should I do?

mint merlin
#

yes, I usually like to create a separate tasks module and keep my cron methods there. it makes them easier to find and maintain.

sharp mantle
#

Perfect, that solved my problem, thank you very much!