A NestJS module for scheduling Bull jobs using cron expressions
MIT License
A NestJS module for scheduling Bull jobs using cron expressions
npm install nest-schedule-bull
Modern applications often require reliable and efficient job scheduling to automate repetitive tasks, manage background processes, and enhance overall system performance. Nest Schedule Bull is motivated by the need for a flexible and scalable solution that seamlessly integrates with NestJS and leverages the robust capabilities of the Bull job queue.
Benefits over @nestjs/schedule
First you need to import the module in your app.module.ts
file:
import { Module } from "@nestjs/common";
import { ScheduleBullModule } from "nest-schedule-bull";
@Module({
imports: [
ScheduleBullModule.forRoot({
host: "localhost",
port: 6379,
}),
],
})
export class AppModule {}
Then you can use the @Cron()
decorator to schedule your jobs:
import { Injectable, Logger } from "@nestjs/common";
import { Cron, CronExpression } from "nest-schedule-bull";
@Injectable()
export class AppService {
private logger = new Logger(AppService.name);
@Cron(CronExpression.EVERY_10_SECONDS)
public async doSomething(): Promise<void> {
this.logger.log("Doing something...");
}
}
If you need check the status of your jobs, you can use the following decorators:
import { Injectable, Logger } from "@nestjs/common";
import {
Cron,
CronExpression,
OnQueueActive,
OnQueueCompleted,
OnQueueError,
OnQueueFailed,
OnQueueProgress,
} from "nest-schedule-bull";
@Injectable()
export class AppService {
private logger = new Logger(AppService.name);
@Cron(CronExpression.EVERY_10_SECONDS)
public async doSomething(): Promise<void> {
this.logger.log("Doing something...");
}
@OnQueueActive()
public onActive(job: Job): void {
this.logger.log(`Job ${job.id} is active`);
}
@OnQueueCompleted()
public onCompleted(job: Job): void {
this.logger.log(`Job ${job.id} is completed`);
}
@OnQueueError()
public onError(job: Job, error: Error): void {
this.logger.log(`Job ${job.id} has failed with error ${error.message}`);
}
@OnQueueFailed()
public onFailed(job: Job, error: Error): void {
this.logger.log(`Job ${job.id} has failed with error ${error.message}`);
}
@OnQueueProgress()
public onProgress(job: Job): void {
this.logger.log(`Job ${job.id} is ${job.progress}% done`);
}
}
nest-schedule-bull
is MIT licensed.