Utility for defining cron jobs as providers in a central place.
The example below is for a simple use case. The main advantage of using this package in a mono repo, where there are multiple applications that use multiple libraries. Libraries or the application is responsible for defining the cron jobs. With the cron provider, the cron jobs can be easily created and shared between the applications.
cron.provider.ts
import { CronProvider, CronProviderBuilder } from "@zonneplan/nest-schedule-cron-utility";
import { CronJob } from "cron";
import { myOtherCronProvider } from "./my-other-cron.provider";
const myProvider: CronProvider = {
provide: 'my_cron_job',
useFactory: () => (
{
name: 'my_cron_job',
job: CronJob.from({
cronTime: '* * * * *',
onTick: () => console.log('tick'),
})
}
)
}
export const cronProviders = new CronProviderBuilder()
.addProvider(myProvider)
.addProvider(myOtherCronProvider.provide)
.build()
my.module.ts
import { Module } from "@nestjs/common";
import { ScheduleModule } from "@nestjs/schedule";
import { cronProviders } from "./cron.provider";
@Module({
imports: [
// ...
ScheduleModule.forRoot(),
// my other module that already provided the myOtherCronProvider
],
providers: [
// ...
...cronProviders,
],
})
export class MyModule {}
main.ts
import { NestFactory } from "@nestjs/core";
import { useCron } from "@zonneplan/nest-schedule-cron-utility";
async function bootstrap() {
const app = await NestFactory.create(AppModule);
// ...
useCron(app);
// ...
await app.listen(3000);
}