cron.ts 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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 | undefined;
  11. /**
  12. * Create and start a new cronjob
  13. */
  14. startCron(): void {
  15. this.cronJob?.stop();
  16. this.cronJob = this.generateCronJob(this.getCronSchedule());
  17. this.cronJob.start();
  18. }
  19. /**
  20. * Stop the current cronjob
  21. */
  22. stopCron(): void {
  23. this.cronJob?.stop();
  24. this.cronJob = undefined;
  25. }
  26. isJobRunning(): boolean {
  27. return this.cronJob != null;
  28. }
  29. /**
  30. * Get the cron schedule
  31. * e.g. '0 1 * * *'
  32. */
  33. abstract getCronSchedule(): string;
  34. /**
  35. * Execute the job. Define the job process in the subclass.
  36. */
  37. abstract executeJob(): Promise<void>;
  38. /**
  39. * Create a new cronjob
  40. * @param cronSchedule e.g. '0 1 * * *'
  41. */
  42. protected generateCronJob(cronSchedule: string): ScheduledTask {
  43. return nodeCron.schedule(cronSchedule, async () => {
  44. try {
  45. await this.executeJob();
  46. } catch (e) {
  47. logger.error(e);
  48. }
  49. });
  50. }
  51. }
  52. export default CronService;