Careeroza
Scheduling with Cron
@nestjs/schedule
Example
npm i @nestjs/scheduleExample output
added 2 packages in 2s
src/tasks/tasks.service.ts
import { Injectable, Logger } from '@nestjs/common';
import { Cron, CronExpression, Interval } from '@nestjs/schedule';
@Injectable()
export class TasksService {
private readonly logger = new Logger(TasksService.name);
constructor(private readonly orders: OrdersService, private readonly reports: ReportsService) {}
// every day at 02:00 India time
@Cron('0 2 * * *', { name: 'daily-sales-report', timeZone: 'Asia/Kolkata' })
async dailyReport() {
await this.reports.emailDailySales();
}
@Cron(CronExpression.EVERY_10_MINUTES)
async cancelUnpaidOrders() {
const count = await this.orders.cancelPendingOlderThan(30); // minutes
this.logger.log(`cancelled ${count} unpaid orders`);
}
@Interval(60_000)
heartbeat() {
this.logger.debug('scheduler alive');
}
}
// app.module.ts: imports: [ScheduleModule.forRoot()]| Cron | Meaning |
|---|---|
0 2 * * * | Every day at 02:00 |
*/10 * * * * | Every 10 minutes |
0 9 * * 1 | Mondays at 09:00 |
0 0 1 * * | First day of each month at midnight |
Note: If you run 3 instances of the API, each cron fires 3 times. Run scheduled jobs in only one instance (an env flag like RUN_CRON=true), or make the cron just add a BullMQ job with a fixed jobId so duplicates are ignored.