Scheduling Tasks in Nest.js with Cron Jobs
A Beginner's Guide to Cron Job Integration in Nest.js Projects
Introduction
In the realm of backend development, the ability to schedule tasks at specific times or intervals is often a critical requirement. Nest.js, a versatile Node.js framework, meets this need with its seamless integration of cron jobs. Cron, a time-based job scheduler found in Unix-like operating systems, empowers developers to schedule tasks to run periodically at fixed times, dates, or intervals. This blog aims to provide a comprehensive guide on utilizing cron jobs in Nest.js to efficiently schedule and manage recurring tasks within your application.
Setting Up a Nest.js Project
npm install -g @nestjs/cli
nest new nest-cron-example
cd nest-cron-example
Next, install the required dependencies.
npm install --save @nestjs/schedule
Before start using nestjs/schedule package we need to import in app.module.ts
// app.module.ts
import { Module } from '@nestjs/common';
import { ScheduleModule } from '@nestjs/schedule';
@Module({
imports: [
ScheduleModule.forRoot()
],
})
export class AppModule {}
Creating a Cron Service
In Nest.js, a service can be created to handle cron jobs. Let's generate a new service named CronService
:
nest generate service cron
Now, open the cron.service.ts
file and add a method to schedule a cron job:
import { Injectable, Logger } from '@nestjs/common';
import { Cron, CronExpression } from '@nestjs/schedule';
@Injectable()
export class CronService {
private readonly logger = new Logger(CronService.name);
@Cron(CronExpression.EVERY_5_SECONDS)
cronisRunning() {
this.logger.log('Cron job running...');
}
}
In this example, we've created a new cron job that runs every 5 seconds.
Using the Cron Service
To utilize our CronService
, we need to add it to a module. Open the app.module.ts
file and import the CronService
:
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { CronService } from './cron/cron.service';
import { ScheduleModule } from '@nestjs/schedule';
@Module({
imports: [ScheduleModule.forRoot()],
controllers: [AppController],
providers: [AppService, CronService],
})
export class AppModule {}
Upon running your Nest.js application, you should observe the log message from the cron job every 5 seconds.
Conclusion
This guide explores how to schedule and manage recurring tasks in Nest.js using cron jobs. It covers setting up a Nest.js project, creating a Cron Service to handle scheduled tasks, and providing examples of scheduling tasks at various intervals, including a task that runs at midnight every day. Perfect for backend developers looking to implement time-based job scheduling in their applications.