Commit 2ea6b1c1 by imwangxiaozhou

fix(llm_tasks): 修复Celery任务中的asyncio事件循环冲突问题

新增共享事件循环封装函数`_run_async`,复用同一个事件循环运行异步协程,避免多次调用asyncio.run()导致的"attached to a different loop"错误;同时清理了aggregate_call_stats函数中冗余的导入语句。
1 parent 66d1851a
......@@ -3,6 +3,7 @@ import asyncio
import logging
from datetime import datetime
from typing import Optional
from functools import wraps
from celery import Task
from sqlalchemy import select, update
......@@ -210,6 +211,25 @@ async def _process_call(async_task_id: str) -> dict:
}
# 共享事件循环 — Celery 同步进程中复用同一个循环,避免 asyncio.run() 创建/销毁导致的"attached to a different loop" 错误
_shared_loop: Optional[asyncio.AbstractEventLoop] = None
def _run_async(coro):
"""在共享事件循环中运行 async 协程并返回结果"""
global _shared_loop
try:
_shared_loop = asyncio.get_running_loop()
# 当前已有循环(如调试或测试环境),直接运行
return _shared_loop.run_until_complete(coro)
except RuntimeError:
# 没有运行中的循环,创建/复用共享循环
if _shared_loop is None or _shared_loop.is_closed():
_shared_loop = asyncio.new_event_loop()
asyncio.set_event_loop(_shared_loop)
return _shared_loop.run_until_complete(coro)
@celery_app.task(
bind=True,
base=LLMCallTask,
......@@ -226,7 +246,7 @@ def process_async_llm_call(self, async_task_id: str) -> dict:
"""
logger.info(f"开始处理异步任务: async_task_id={async_task_id}")
try:
result = asyncio.run(_process_call(async_task_id))
result = _run_async(_process_call(async_task_id))
logger.info(f"异步任务处理成功: {result}")
return result
except Exception as exc:
......@@ -301,7 +321,7 @@ def rescan_stuck_tasks() -> list[dict]:
"""扫描卡住的任务并重新提交(Celery Beat 定时触发)"""
logger.info("开始扫描卡住任务...")
try:
result = asyncio.run(_rescan_stuck())
result = _run_async(_rescan_stuck())
return result
except Exception as e:
logger.error(f"扫描卡住任务失败: {e}")
......@@ -331,7 +351,6 @@ def aggregate_call_stats() -> dict:
"""每小时聚合:计算上一小时调用统计数据(Celery Beat 定时触发)"""
logger.info("开始每小时聚合统计...")
try:
import asyncio
from app.services.statistics_service import aggregate_hourly
async def _run():
......@@ -339,7 +358,7 @@ def aggregate_call_stats() -> dict:
await aggregate_hourly(db)
await db.commit()
asyncio.run(_run())
_run_async(_run())
logger.info("每小时聚合统计完成")
return {"status": "ok", "agg_type": "hourly"}
except Exception as e:
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!