|
| 1 | +import { |
| 2 | + Injectable, |
| 3 | + OnApplicationBootstrap, |
| 4 | + OnApplicationShutdown, |
| 5 | +} from '@nestjs/common' |
| 6 | +import { DiscoveryService, MetadataScanner, Reflector } from '@nestjs/core' |
| 7 | +import { INTERVAL_HOST_KEY } from './decorators/interval-host.decorator' |
| 8 | +import { INTERVAL_KEY } from './decorators/interval.decorator' |
| 9 | + |
| 10 | +@Injectable() |
| 11 | +export class IntervalScheduler |
| 12 | + implements OnApplicationBootstrap, OnApplicationShutdown |
| 13 | +{ |
| 14 | + private readonly intervals: NodeJS.Timeout[] = [] |
| 15 | + |
| 16 | + constructor( |
| 17 | + private readonly discoveryService: DiscoveryService, |
| 18 | + private readonly reflector: Reflector, |
| 19 | + private readonly metadataScanner: MetadataScanner, |
| 20 | + ) {} |
| 21 | + |
| 22 | + onApplicationBootstrap() { |
| 23 | + const providers = this.discoveryService.getProviders() |
| 24 | + providers.forEach((wrapper) => { |
| 25 | + const { instance } = wrapper |
| 26 | + |
| 27 | + const prototype = instance && Object.getPrototypeOf(instance) |
| 28 | + if (!instance || !prototype) { |
| 29 | + return |
| 30 | + } |
| 31 | + |
| 32 | + const isIntervalHost = |
| 33 | + this.reflector.get(INTERVAL_HOST_KEY, instance.constructor) ?? false |
| 34 | + |
| 35 | + if (!isIntervalHost) { |
| 36 | + return |
| 37 | + } |
| 38 | + |
| 39 | + const methodKeys = this.metadataScanner.getAllMethodNames(prototype) |
| 40 | + |
| 41 | + methodKeys.forEach((methodKey) => { |
| 42 | + const interval = this.reflector.get(INTERVAL_KEY, instance[methodKey]) |
| 43 | + |
| 44 | + if (interval === undefined) { |
| 45 | + return |
| 46 | + } |
| 47 | + |
| 48 | + const intervalRef = setInterval(() => instance[methodKey](), interval) |
| 49 | + this.intervals.push(intervalRef) |
| 50 | + }) |
| 51 | + }) |
| 52 | + } |
| 53 | + |
| 54 | + onApplicationShutdown(signal?: string) { |
| 55 | + this.intervals.forEach((intervalRef) => clearInterval(intervalRef)) |
| 56 | + } |
| 57 | +} |
0 commit comments