apps.py 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. from django.apps import AppConfig
  2. import threading
  3. from apscheduler.schedulers.background import BackgroundScheduler
  4. import time
  5. import logging
  6. import psutil
  7. from django.core.signals import request_finished
  8. from django.dispatch import receiver
  9. class BackendConfig(AppConfig):
  10. default_auto_field = 'django.db.models.BigAutoField'
  11. name = 'backend'
  12. # def ready(self):
  13. # # 导入是为了避免循环导入问题
  14. # from .Service.KbmService import KbmService
  15. #
  16. # # 检查是否在主进程中运行
  17. # if threading.current_thread().name != 'MainThread':
  18. # return
  19. #
  20. # # 启动队列处理线程
  21. # queue_thread = threading.Thread(target=KbmService.process_queue, daemon=True)
  22. # queue_thread.start()
  23. # logging.info("Queue processing thread started")
  24. #
  25. # # self.new_method()
  26. # def ready(self):
  27. # # 导入是为了避免循环导入问题
  28. # from .Service.KbmService import KbmService
  29. #
  30. # # 检查是否在主进程中运行
  31. # if threading.current_thread().name != 'MainThread':
  32. # return
  33. #
  34. # # 启动 RabbitMQ 消费者线程
  35. # consumer_thread = threading.Thread(target=self.start_rabbitmq_consumer, daemon=True)
  36. # consumer_thread.start()
  37. # logging.info("RabbitMQ consumer thread started")
  38. #
  39. # def start_rabbitmq_consumer(self):
  40. # from .Service.KbmService import KbmService
  41. # while True:
  42. # try:
  43. # logging.info("Starting RabbitMQ consumer...")
  44. # KbmService.process_queue()
  45. # except Exception as e:
  46. # logging.error(f"RabbitMQ consumer encountered an error: {str(e)}")
  47. # logging.info("Attempting to restart consumer in 5 seconds...")
  48. # time.sleep(5)
  49. def ready(self):
  50. # 导入是为了避免循环导入问题
  51. from .Service.KbmService import KbmService
  52. # 检查是否在主进程中运行
  53. if threading.current_thread().name != 'MainThread':
  54. return
  55. # 启动 RabbitMQ 监控线程
  56. monitor_thread = threading.Thread(target=KbmService.check_and_process_queue, daemon=True)
  57. monitor_thread.start()
  58. logging.info("RabbitMQ monitor thread started")
  59. def start_scheduler(self):
  60. # 导入 minioTimingService
  61. from .Service.minioTimingService import minioTimingService
  62. # 定义调度器
  63. scheduler = BackgroundScheduler()
  64. # 添加任务到调度器
  65. scheduler.add_job(minioTimingService.rmMiniInfo, 'interval', days=1)
  66. # 启动调度器
  67. scheduler.start()
  68. # 确保在 Django 应用完全加载后启动调度器
  69. scheduler_started = False
  70. @receiver(request_finished)
  71. def start_scheduler(sender, **kwargs):
  72. global scheduler_started
  73. if not scheduler_started:
  74. from django.apps import apps
  75. if apps.ready:
  76. config = apps.get_app_config('backend')
  77. config.start_scheduler()
  78. scheduler_started = True