Using @nestjs/schedule for CRON Jobs: Practical Examples

a very artistic picture of a bird made out of metal

To schedule CRON tasks in a Nest.js application, you can use the @nestjs/schedule package, which provides decorators and utilities for scheduling jobs.

Here’s a step-by-step guide to setting up CRON tasks in Nest.js:

Step 1: Install the Required Packages

First, you need to install the @nestjs/schedule package:

npm install --save @nestjs/schedule

Step 2: Create a CRON Job

Create a new service that will contain your CRON job logic. For example, create a file named cron.service.ts:

// src/cron.service.ts import { Injectable } from ‘@nestjs/common’; import { Cron, CronExpression } from ‘@nestjs/schedule’; @Injectable() export class CronService { @Cron(CronExpression.EVERY_30_MINUTES) handleCron() { // Your CRON job logic goes here console.log(‘Called every 30 minutes’); } }

In this example, handleCron method will run every 30 minutes according to the CRON expression CronExpression.EVERY_30_MINUTES.

Step 3: Register the CRON Module

Modify your module (app.module.ts) to register the ScheduleModule and your CronService:

// src/app.module.ts import { Module } from ‘@nestjs/common’; import { ScheduleModule } from ‘@nestjs/schedule’; import { CronService } from ‘./cron.service’; @Module({ imports: [ScheduleModule.forRoot()], providers: [CronService], }) export class AppModule {}

Step 4: Run your Nest.js Application

Start your Nest.js application:

npm run start

Now, your CRON job defined in CronService will run according to the specified schedule.

Additional Tips:

  • CRON Expressions: Use CronExpression constants (e.g., CronExpression.EVERY_30_MINUTES) for common schedules. You can also specify custom CRON expressions for more specific schedules.
  • Dependency Injection: You can inject other Nest.js services into your CRON service just like any other service.
  • Testing CRON Jobs: Test your CRON jobs as you would test other parts of your Nest.js application. Consider mocking dependencies for unit testing.

By following these steps, you can easily schedule and run CRON jobs within your Nest.js application using the @nestjs/schedule package.

Also Read:

Leave a Reply

Your email address will not be published. Required fields are marked *

Share this article:

RSS2k
Follow by Email0
Facebook780
Twitter3k
120
29k
130k

Also Read: