from django.apps import AppConfig import threading from apscheduler.schedulers.background import BackgroundScheduler import time import logging import psutil from django.core.signals import request_finished from django.dispatch import receiver class BackendConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'backend' # def ready(self): # # 导入是为了避免循环导入问题 # from .Service.KbmService import KbmService # # # 检查是否在主进程中运行 # if threading.current_thread().name != 'MainThread': # return # # # 启动队列处理线程 # queue_thread = threading.Thread(target=KbmService.process_queue, daemon=True) # queue_thread.start() # logging.info("Queue processing thread started") # # # self.new_method() # def ready(self): # # 导入是为了避免循环导入问题 # from .Service.KbmService import KbmService # # # 检查是否在主进程中运行 # if threading.current_thread().name != 'MainThread': # return # # # 启动 RabbitMQ 消费者线程 # consumer_thread = threading.Thread(target=self.start_rabbitmq_consumer, daemon=True) # consumer_thread.start() # logging.info("RabbitMQ consumer thread started") # # def start_rabbitmq_consumer(self): # from .Service.KbmService import KbmService # while True: # try: # logging.info("Starting RabbitMQ consumer...") # KbmService.process_queue() # except Exception as e: # logging.error(f"RabbitMQ consumer encountered an error: {str(e)}") # logging.info("Attempting to restart consumer in 5 seconds...") # time.sleep(5) def ready(self): # 导入是为了避免循环导入问题 from .Service.KbmService import KbmService # 检查是否在主进程中运行 if threading.current_thread().name != 'MainThread': return # 启动 RabbitMQ 监控线程 monitor_thread = threading.Thread(target=KbmService.check_and_process_queue, daemon=True) monitor_thread.start() logging.info("RabbitMQ monitor thread started") def start_scheduler(self): # 导入 minioTimingService from .Service.minioTimingService import minioTimingService # 定义调度器 scheduler = BackgroundScheduler() # 添加任务到调度器 scheduler.add_job(minioTimingService.rmMiniInfo, 'interval', days=1) # 启动调度器 scheduler.start() # 确保在 Django 应用完全加载后启动调度器 scheduler_started = False @receiver(request_finished) def start_scheduler(sender, **kwargs): global scheduler_started if not scheduler_started: from django.apps import apps if apps.ready: config = apps.get_app_config('backend') config.start_scheduler() scheduler_started = True