schedule-event-mongo
v0.0.408
Published
Execute scheduled events from multiple instances environment using mongo as semaphore
Maintainers
Readme
About
NestJS module for scheduling events and ensure only 1 event is emitted using mongodb.
Dependencies
- @nestjs/mongoose
- @nestjs/event-emitter
- @nestjs/schedule
How to use
Name your events (this is optional but recommended):
// if you prefer enums...
export enum MyEvents {
EventNameFoo = 'EventNameFoo',
}
// if you dont like enums use constants:
export const MyEventNameFoo = 'EventNameFoo';
// if you dont like constants use object literals:
export const MyEvents = {
EventNameFoo: 'EventNameFoo',
}Register the module within the module you want to use it:
// ... inside module imports array
ScheduleEventModule.register([
{
eventName: MyEvents.EventName, // the event name as you decided to define it
cronExpression: CronExpression.EVERY_DAY_AT_MIDNIGHT, // frequency to schedule
},
])
// ...Create the appropriate event handler:
@Injectable()
export class MyServiceThatDoesThings {
@OnEvent(MyEvents.EventName)
async handleMyEventName(eventData: ScheduleEventData) {
// ... do stuff
}
}In you main app module import both, ScheduleModule and EventEmitterModule:
@Module({
imports: [
EventEmitterModule.forRoot(),
ScheduleModule.forRoot(),
//...
})
export class AppModule{}What's the purpose?
This repository provides an opinionated solution for executing scheduled events in a distributed environment where multiple instances of an application are running simultaneously. It uses MongoDB as a semaphore to ensure that scheduled events are executed exactly once, preventing duplicate executions across different instances.
The module integrates with NestJS's scheduling and event emitter systems, allowing you to:
- Define scheduled events using cron expressions
- Ensure single execution across multiple application instances
- Track event execution history in MongoDB
- Handle scheduled events using event-driven patterns
TODO
Create unit tests.
