import { Injectable } from "@nestjs/common";
import { CronJob } from "cron";
import { SchedulerRegistry } from "@nestjs/schedule";
@Injectable()
export class CronService {
constructor(private schedulerRegistry: SchedulerRegistry) {}
public async scheduleSendNotification(
hour: string,
minutes: String,
jobName: string,
day: string,
month: string
) {
const job = new CronJob(
`0 ${minutes} ${hour} ${day} ${month} *`,
async () => {
console.log("Cron job executed successfully. ");
}
);
this.schedulerRegistry.addCronJob(jobName, job);
job.start();
console.log(` Cron will execute at ${hours}:${minutes}. `);
}
}
In this, we use the CronJob object from the cron package to create the cron job. The CronJob constructor takes a cron pattern (just like the
@Cron()
decorator) as its first argument, and a callback to be executed when the cron timer fires as its second argument. The SchedulerRegistry.addCronJob() method takes two arguments: a name for the CronJob, and the CronJob object itself.
JobName should be unique if scheduled cron not executed.
For more visit: