nest-schedule npm not working

Viewed 7577

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

5 Answers

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",

Had the same issue, cron jobs did not start, solved it this way:

async function bootstrap() {

  const app = await NestFactory.createApplicationContext(AppModule);
  
  // add this, if network if network listener is needed :
  await app.listen(<port>)

  // or this if network is not needed :
  await app.init()

}

bootstrap();

@Cron() and @Schedule() decorators did not really work until v0.3.1 (github issue).

Could you try the latest version?

package.json

{
    ...
    "dependencies": {
        "nest-schedule": "^0.3.1"
        ...
    }
    ...
}

scheduler.service.ts

import { Injectable } from '@nestjs/common';
import { Cron, NestSchedule } from 'nest-schedule';

@Injectable()
export class SchedulerService extends NestSchedule {

    // ...

    @Cron('* * * * * *') // Run every second
    scheduledJob() {
        console.info('[Scheduler]: scheduled jobs has been started');

        // ...
    }

    // ...

}

Works for me.

I had the same issue... Doing some research I found I need to use the latest version of @nestjs/common and @nestjs/core and if used also @nestjs/platform-express

Related