# Scheduling Tasks in Nest.js with Cron Jobs

## **Introduction**

In the realm of [backend](https://www.bytescrum.com/) development, the <mark>ability to schedule tasks at specific times or intervals</mark> is often a critical requirement. Nest.js, a versatile Node.js framework, meets this need with its seamless integration of [cron](https://docs.nestjs.com/techniques/task-scheduling) jobs. [Cron](https://princeigwe.medium.com/automating-tasks-with-cron-jobs-and-nestjs-6fd8db07f568), 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](https://blog.bytescrum.com/) 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**

```bash
npm install -g @nestjs/cli
nest new nest-cron-example
cd nest-cron-example
```

Next, install the required dependencies.

```bash
npm install --save @nestjs/schedule
```

Before start using nestjs/schedule package we need to import in app.module.ts

```typescript
// 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`:

```bash
nest generate service cron
```

Now, open the `cron.service.ts` file and add a method to schedule a cron job:

```typescript
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](https://tharuneshwar.medium.com/nestjs-task-scheduling-cron-job-56326b36ee4e) 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`:

```typescript
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.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1713421895412/0c83ef31-2155-43c4-98c5-bf88c0d04474.png align="center")

 <details data-node-type="hn-details-summary"><summary> Conclusion</summary><div data-type="detailsContent">Mastering task scheduling with cron jobs in Nest.js opens up a world of possibilities for building robust and scalable backend systems. By exploring advanced examples like dynamic job scheduling, batch processing, rate-limited API requests, and distributed task scheduling, developers can harness the full potential of Nest.js for efficient backend management. With careful planning and implementation, cron jobs empower developers to automate complex workflows and optimize resource utilization in their Nest.js applications.</div></details>

> 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.
