NestJS Task Scheduling (Cron Job)
1. Introduction
This document presents a comprehensive guide and Proof of Concept (PoC) for implementing task scheduling in a NestJS application using the @nestjs/schedule
package. Task scheduling allows for the automation and management of tasks at specific times or intervals within the application.
2. When to Use Task Scheduling
Task scheduling should be used when there is a need to automate and manage tasks in an application at specific times or intervals. For instance, in a news website application, task scheduling can be employed to fetch and update news articles at regular intervals, such as every hour.
3. What is a Cron Job?
A cron job is a time-based job scheduler that automates and schedules tasks to run at specific intervals, times, or days. These scheduled tasks are commonly referred to as “cron jobs.”
4. Setup
4.1 Installation
To set up task scheduling in a NestJS application, follow these installation steps:
npm install --save @nestjs/schedule
npm install --save-dev @types/cron
4.2 Configuration
Incorporate the @nestjs/schedule
package into your NestJS application by importing the necessary modules and initializing the ScheduleModule
.
import { Injectable } from "@nestjs/common";
import { Cron, SchedulerRegistry } from "@nestjs/schedule";
import { Logger } from "@nestjs/common";
// Initialize ScheduleModule in your AppModule or app.module.ts file
@Module({
imports: [ScheduleModule.forRoot()],
})
export class AppModule {}
5. Implementation
5.1 Creating a Task Service
In a NestJS service, tasks can be scheduled and managed. Use the @Cron
decorator to create scheduled tasks.
// src/task/task.service.ts
import { Injectable } from '@nestjs/common';
import { Cron, CronExpression } from '@nestjs/schedule';@Injectable()
export class TaskService {
@Cron(CronExpression.EVERY_10_MINUTES)
handleEvery10Minutes() {
console.log('Task executed every 10 minutes');
} @Cron('45 * * * * *')
handleEvery45Seconds() {
console.log('Task executed every 45 seconds');
}
}
5.2 Creating Cron Jobs
Cron jobs can be created using the @Cron
decorator, specifying the desired cron expression.
- Create a CronJob that automatically runs when the server starts.
- Create a CronJob that activates every 45 seconds after the server starts running.
Use */<your seconds>
to run tasks at specific intervals.
5.3 Using Cron Expressions
Cron expressions allow fine-grained control over task scheduling. Examples of cron expressions include:
0 */10 * * * *
: Runs every 10 minutes from the server start.- Alternative ways, alias, range values,
#
expression, and?
expression are explained in detail in the document.
6. Scheduler Registry
The Scheduler Registry manages the lifecycle of scheduled tasks and cron jobs in NestJS applications, allowing for their creation, execution, and removal. It can be injected into a class using dependency injection.
6.1 Commonly Used Methods
addCronJob
: Adds a cron job instance to the registry.deleteCronJob
: Deletes a cron job instance from the registry.getCronJob
: Retrieves a cron job instance from the registry.getCronJobs
: Retrieves all cron job instances from the registry.
7. Dynamic Cron Job
A dynamic cron job is a scheduled task that can be created, updated, or deleted programmatically during runtime.
8. Managing Cron Jobs
8.1 Stopping Cron Jobs
To stop a cron job:
CronJobInstance.stop()
8.2 Deleting Cron Jobs
To delete a cron job:
this.schedulerRegistry.deleteCronJob(jobName)
8.3 Getting All Cron Jobs
To get all cron jobs:
this.schedulerRegistry.getCronJobs()
8.4 Updating Cron Jobs
To update a cron job, retrieve the existing cron job by name and update its cron expression using setTime
.
9. Validating Cron Expressions
Cron expressions can be validated using the cron-validator
package. It checks if a given cron expression is valid.
10. Conclusion
This Proof of Concept demonstrates how to implement task scheduling in a NestJS application using the @nestjs/schedule
package. By following the provided steps and examples, tasks can be automated and managed effectively within the application.