crons.service.ts 1.0 KB

12345678910111213141516171819202122232425262728
  1. import { Injectable } from '@nestjs/common';
  2. import { EventsGateway } from '../events/events.gateway';
  3. import { Cron, CronExpression, SchedulerRegistry } from '@nestjs/schedule';
  4. import { CollectionsService } from '../collections/collections.service';
  5. import { WS_EVENTS, WS_EVENTS_TYPE } from 'src/utils/Const';
  6. @Injectable()
  7. export class CronsService {
  8. constructor(
  9. private eventService: EventsGateway,
  10. private collectionService: CollectionsService,
  11. private schedulerRegistry: SchedulerRegistry,
  12. ) {}
  13. async toggleCronJobByName(data: { name: string; type: WS_EVENTS_TYPE }) {
  14. const { name, type } = data;
  15. const cronJob = this.schedulerRegistry.getCronJob(name);
  16. return Number(type) === WS_EVENTS_TYPE.STOP
  17. ? cronJob.stop()
  18. : cronJob.start();
  19. }
  20. @Cron(CronExpression.EVERY_SECOND, { name: WS_EVENTS.COLLECTION })
  21. async getCollections() {
  22. const res = await this.collectionService.getAllCollections();
  23. this.eventService.server.emit(WS_EVENTS.COLLECTION, res);
  24. return res;
  25. }
  26. }