For current version of Nest may you could use nestjs/schedule. See how I achieve this with nestjs/schedule.
1st: install nestjs cli
npm i -g @nestjs/cli
2nd: Create a new project
nest new schedule-sample
3rd: Install the nestjs schedule
npm install --save @nestjs/schedule
4th: Generate a new service to put your service.
nest generate service cron
Once you have installed the package add it to the app.module as follow below:
import { Module } from '@nestjs/common';
import { ScheduleModule } from '@nestjs/schedule';
import { Logger } from '@nestjs/common';
@Module({
imports: [
ScheduleModule.forRoot()
],
})
export class AppModule {}
5th: you can run it as show bellow (the complete instructions are here https://docs.nestjs.com/techniques/task-scheduling):
@Cron('*/5 * * * * *')
runEvery10Seconds() {
console.log('Run it every 5 seconds');
}
Here is the complete sample (cron.service.ts).
import { Logger } from '@nestjs/common';
import { Injectable } from '@nestjs/common';
import { Cron, Interval } from '@nestjs/schedule';
@Injectable()
export class CronService {
private readonly logger = new Logger(CronService.name);
@Cron('*/5 * * * * *')
runEvery10Seconds() {
this.logger.debug('Run it every 5 seconds');
}
@Cron('10 * * * * *')
handleCron() {
this.logger.debug('Called when the current second is 10');
}
@Interval(10000)
handleInterval() {
this.logger.debug('Called every 10 seconds');
}
}
Final thoughts:
The most sophisticated way to schedule jobs is use dynamic cron jobs. For that you can obtain a reference to a CronJob instance by name from anywhere in your code using the SchedulerRegistry API. First, inject SchedulerRegistry using standard constructor injection:
constructor(private schedulerRegistry: SchedulerRegistry) {}
HINT
Import the SchedulerRegistry from the @nestjs/schedule package.
Then use it in a class as follows. Assume a cron job was created with the following declaration:
@Cron('* * 8 * * *', {
name: 'notifications',
})
triggerNotifications() {}
Access this job using the following:
const job = this.schedulerRegistry.getCronJob('notifications');
job.stop();
console.log(job.lastDate());
I have tested it at the follow versions (package.json)
"@nestjs/common": "^7.6.15",
"@nestjs/core": "^7.6.15",
"@nestjs/schedule": "^0.4.3",