Automating Tasks in NestJS with Cron Jobs

KATHISH KUMARAN R
YavarTechWorks
Published in
3 min readMay 11, 2024

Introduction:

In modern web applications, automating repetitive tasks is essential for improving efficiency and maintaining system health. Cron jobs provide a convenient way to schedule and execute tasks at specific intervals. In this guide, we’ll explore how to implement cron jobs in NestJS, a powerful framework for building server-side applications with Node.js. We’ll cover the fundamentals of cron jobs, their implementation in NestJS, and provide practical examples to demonstrate their usage.

Step 1: Setting Up a NestJS Project

First, ensure you have Node.js and npm installed on your system. You can install NestJS CLI globally using npm:

npm install -g @nestjs/cli

Create a new NestJS project using the CLI:

nest new nest-cron-job

Navigate to the project directory:

cd nest-cron-job

Step 2: Installing Dependencies

NestJS provides built-in support for cron jobs through the @nestjs/schedule package. Install it along with its peer dependencies:

npm install --save @nestjs/schedule rxjs

Note: The rxjs package is installed as a peer dependency along with @nestjs/schedule. This is because @nestjs/schedule internally uses RxJS observables for managing cron jobs and scheduling tasks asynchronously.

Step 3: Implementing a Cron Job

Create a new service to handle the cron job. For example, let’s create a task.service.ts file in the src directory:

// src/task.service.ts

import { Injectable, Logger } from '@nestjs/common';
import { Cron } from '@nestjs/schedule';

@Injectable()
export class TaskService {
private readonly logger = new Logger(TaskService.name);

@Cron('0 * * * * *')
handleCron() {
this.logger.debug('Called every minute');
}
}

In this example, the handleCron() method will be executed every minute according to the cron expression '0 * * * * *'.

Step 4: Registering the Cron Job Provider

Register the TaskService provider in your module. Open the app.module.ts file and import the ScheduleModule:

// src/app.module.ts

import { Module } from '@nestjs/common';
import { ScheduleModule } from '@nestjs/schedule';
import { TaskService } from './task.service';

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

Step 5: Testing the Cron Job

You can now run your NestJS application and observe the cron job in action. Start the application using the following command:

npm run start

You should see the log message 'Called every minute' being printed to the console every minute, indicating that the cron job is running successfully.

Practical Examples

Consider some practical examples of cron jobs in NestJS:

  1. Sending daily email reminders to users.
  2. Cleaning up expired session data from the database.
  3. Generating weekly reports and storing them in a designated folder.

Conclusion:

By following the steps outlined in this guide, you’ve learned how to implement cron jobs in NestJS to automate tasks at specific intervals. Whether it’s performing routine maintenance, generating reports, or sending notifications, cron jobs streamline operations and enhance the efficiency of your NestJS applications. Experiment with different cron expressions and task implementations to tailor cron jobs to your specific use case.

Now you’re equipped with the knowledge to incorporate cron jobs into your NestJS projects and automate tasks effectively.

Thank You For Reading this Post………

Have a Nice Day……

👋👋👋

--

--