I am using nest.js framework for developing a node based application. I am trying to write a scheduler using nest-schedule as mentioned at https://www.npmjs.com/package/nest-schedule.
Somehow the code is not working when used with @Cron or @Schedule. Rest other decorators work's fine. Using the same code base as mentioned in above link. Can anyone help me with setting this up and with exact cron pattern used in nodejs
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",
Have you added your job's service to a module?
https://github.com/nestjs/nest/tree/master/sample/27-scheduling/src/tasks
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With