I have a simple NestJS web app. I have coded my own simple task scheduler and injected it in a global module. It's quite simple really, you just pass it a function and a date and it will execute the function at the given date or in a recurring fashion if you pass some other options.
scheduler.add(myFunc, myDate);
My project is structured by feature modules and each feature modules has its own controllers and services. Some tasks are added to the scheduler as a result of an http request and in that case it is quite simple to add the task, you do it right in the service method handling the related request. But some tasks, especially some recurring tasks, need to be added at application or module loading. I was planning to have a file associated with each feature module that would contain all the recurring tasks that need to get registered with my scheduler at application or module loading. My first instinct was that the file could look something like this:
feature.scheduled-tasks.ts
import { Scheduler } from './src/scheduler';
import { Model } from '@nestjs/common';
import { UserModel } from '.src/who/cares/you/get/the/idea';
import { SomeService } from '.src/see/above';
// I need Nest to inject the Scheduler here
const scheduler: Scheduler
// I need Nest to inject some other feature related providers here,
// like Mongoose database models and other services
const userModel: Model<UserModel>;
const someService: SomeService;
const firstTask = () => {
// do stuff using the userModel
}
const secondTask = () => {
// do stuff using someService
}
scheduler.add(firstTask, {units: 5, measure: 'dayOfMonth'});
scheduler.add(secondTask, {units: 17, measure: 'dayOfMonth'});
I have two problems / questions in getting this to work:
- How do I get Nest to inject the providers that I need in this file?
- How do I tell Nest to run the contents of this file upon application or feature module load?