thread-deletion-cron.ts 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import nodeCron from 'node-cron';
  2. import { configManager } from '~/server/service/config-manager';
  3. import loggerFactory from '~/utils/logger';
  4. import { getOpenaiService, type IOpenaiService } from './openai';
  5. const logger = loggerFactory('growi:service:thread-deletion-cron');
  6. const DELETE_LIMIT = 100;
  7. class ThreadDeletionCronService {
  8. cronJob: nodeCron.ScheduledTask;
  9. openaiService: IOpenaiService;
  10. startCron(): void {
  11. const isAiEnabled = configManager.getConfig('crowi', 'app:aiEnabled');
  12. if (!isAiEnabled) {
  13. return;
  14. }
  15. // Executed at 0 minutes of every hour
  16. // const cronSchedule = '0 * * * *';
  17. // debug mode
  18. const cronSchedule = '* * * * *';
  19. this.cronJob?.stop();
  20. this.cronJob = this.generateCronJob(cronSchedule);
  21. this.cronJob.start();
  22. }
  23. private async executeJob(): Promise<void> {
  24. const openaiService = getOpenaiService();
  25. // Delete only 100 by rateLimit countermeasure on OpenAI side
  26. await openaiService?.deleteExpiredThreads(DELETE_LIMIT);
  27. }
  28. private generateCronJob(cronSchedule: string) {
  29. return nodeCron.schedule(cronSchedule, async() => {
  30. try {
  31. await this.executeJob();
  32. }
  33. catch (e) {
  34. logger.error(e);
  35. }
  36. });
  37. }
  38. }
  39. export default ThreadDeletionCronService;