How to setup Cron in NestJs

Table of contents

No heading

No headings in the article.

Hello everyone, I am so excited to write the first blog on hashnode. Any kind of feedback or inputs is most welcome. So, let's start the blog about cron jobs. First of all, a cron is a kind of background process, which processes your data in the background without interfering with your user's UI.

When we need Cron? Suppose you want to check if any user's subscribed plan is expired or not at every 10 minute. Then you have to check this from a background process. Cron job runs in the background.

To use Crons in NestJs, Nest provides an in-build module "schedule". To install the schedule use this command.

npm install --save @nestjs/schedule Now add this module to module.ts file like this:

import { Module } from '@nestjs/common';
import { ScheduleModule } from '@nestjs/schedule';

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

That's it for the configuration. You are ready to add your first cron. You can add cron with below command anywhere in your modules.

@Cron('*/5 * * * * *') runEvery5Seconds() { console.log('Every 5 seconds'); } Now, this function will call at every 5 second and perform your desired operation.

I hope you guys like the blog, do let me know. Thanks...