cron.ts 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import type { ScheduledTask } from 'node-cron';
  2. import nodeCron from 'node-cron';
  3. import loggerFactory from '~/utils/logger';
  4. const logger = loggerFactory('growi:service:cron');
  5. /**
  6. * Base class for services that manage a cronjob
  7. */
  8. abstract class CronService {
  9. // The current cronjob to manage
  10. cronJob: ScheduledTask;
  11. /**
  12. * Create and start a new cronjob
  13. * @param cronSchedule e.g. '0 1 * * *'
  14. */
  15. startCron(cronSchedule: string): void {
  16. this.cronJob?.stop();
  17. this.cronJob = this.generateCronJob(cronSchedule);
  18. this.cronJob.start();
  19. }
  20. /**
  21. * Stop the current cronjob
  22. */
  23. stopCron(): void {
  24. this.cronJob.stop();
  25. }
  26. /**
  27. * Execute the job. Define the job process in the subclass.
  28. */
  29. abstract executeJob(): Promise<void>;
  30. /**
  31. * Create a new cronjob
  32. * @param cronSchedule e.g. '0 1 * * *'
  33. */
  34. protected generateCronJob(cronSchedule: string): ScheduledTask {
  35. return nodeCron.schedule(cronSchedule, async() => {
  36. try {
  37. await this.executeJob();
  38. }
  39. catch (e) {
  40. logger.error(e);
  41. }
  42. });
  43. }
  44. }
  45. export default CronService;