from time import sleep import sys import config import biz.task from telemetry import init_opentelemetry from services import DefaultTemplateService from util import api import os import glob # 使用新的服务容器架构 from services.service_container import get_template_service, register_default_services # 确保服务已注册 register_default_services() template_service = get_template_service() # Check for redownload parameter if "redownload" in sys.argv: print("Redownloading all templates...") try: for template_name in template_service.get_all_templates().keys(): print(f"Redownloading template: {template_name}") if not template_service.download_template(template_name): print(f"Failed to download template: {template_name}") print("Template redownload process completed!") except Exception as e: print(f"Error during template redownload: {e}") sys.exit(1) sys.exit(0) import logging LOGGER = logging.getLogger(__name__) init_opentelemetry() def cleanup_temp_files(): """清理临时文件 - 异步执行避免阻塞主循环""" import threading def _cleanup(): for file_globs in ["*.mp4", "*.ts", "tmp_concat*.txt"]: for file_path in glob.glob(file_globs): try: if os.path.exists(file_path): os.remove(file_path) LOGGER.debug(f"Deleted temp file: {file_path}") except Exception as e: LOGGER.warning(f"Error deleting file {file_path}: {e}") # 在后台线程中执行清理 threading.Thread(target=_cleanup, daemon=True).start() def main_loop(): """主处理循环""" while True: try: print("waiting for task...") task_list = api.sync_center() if len(task_list) == 0: # 异步清理临时文件 cleanup_temp_files() sleep(5) continue for task in task_list: task_id = task.get("id", "unknown") print(f"Processing task: {task_id}") try: biz.task.start_task(task) LOGGER.info(f"Task {task_id} completed successfully") except Exception as e: LOGGER.error(f"Task {task_id} failed: {e}", exc_info=True) # 继续处理下一个任务而不是崩溃 except KeyboardInterrupt: LOGGER.info("Received shutdown signal, exiting...") break except Exception as e: LOGGER.error("Unexpected error in main loop", exc_info=e) sleep(5) # 避免快速循环消耗CPU if __name__ == "__main__": try: main_loop() except Exception as e: LOGGER.critical("Critical error in main process", exc_info=e) sys.exit(1)