What is @nestjs/schedule?
@nestjs/schedule is a scheduling module for NestJS applications that allows you to easily create and manage scheduled tasks. It provides decorators and utilities to define cron jobs, timeouts, and intervals in a declarative way.
What are @nestjs/schedule's main functionalities?
Cron Jobs
This feature allows you to define cron jobs using the @Cron decorator. The example demonstrates a task that runs every 10 seconds.
```typescript
import { Injectable } from '@nestjs/common';
import { Cron, CronExpression } from '@nestjs/schedule';
@Injectable()
export class TasksService {
@Cron(CronExpression.EVERY_10_SECONDS)
handleCron() {
console.log('Called every 10 seconds');
}
}
```
Timeouts
This feature allows you to define one-time tasks that execute after a specified delay using the @Timeout decorator. The example demonstrates a task that runs once after 5 seconds.
```typescript
import { Injectable } from '@nestjs/common';
import { Timeout } from '@nestjs/schedule';
@Injectable()
export class TasksService {
@Timeout(5000)
handleTimeout() {
console.log('Called once after 5 seconds');
}
}
```
Intervals
This feature allows you to define recurring tasks that execute at specified intervals using the @Interval decorator. The example demonstrates a task that runs every 10 seconds.
```typescript
import { Injectable } from '@nestjs/common';
import { Interval } from '@nestjs/schedule';
@Injectable()
export class TasksService {
@Interval(10000)
handleInterval() {
console.log('Called every 10 seconds');
}
}
```
Other packages similar to @nestjs/schedule
node-cron
node-cron is a lightweight npm package for scheduling tasks in Node.js using cron syntax. It is not specific to any framework and can be used in any Node.js application. Compared to @nestjs/schedule, node-cron provides a more general-purpose solution but lacks the integration and decorators provided by NestJS.
agenda
Agenda is a job scheduling package for Node.js with MongoDB as a backend. It provides a more feature-rich solution for job scheduling, including job persistence, retries, and job prioritization. Compared to @nestjs/schedule, Agenda offers more advanced features but requires additional setup and configuration.
bull
Bull is a Redis-based queue system for Node.js that supports job scheduling, retries, and concurrency. It is designed for handling background jobs and tasks. Compared to @nestjs/schedule, Bull is more suitable for complex job processing scenarios and provides more control over job execution and management.