This commit is contained in:
27942
2026-03-03 02:40:03 +08:00
parent 8c10ded6c7
commit 316e1f7bc4

View File

@@ -9,6 +9,7 @@ import logging
import time
from typing import List, Optional
from asgiref.sync import sync_to_async
from common.protocol import MsgType, TaskStatus, make_msg
from server.models import TaskCreate, Task
@@ -75,6 +76,31 @@ class TaskDispatcher:
# ─── 创建任务 ───
@staticmethod
@sync_to_async
def _mark_dispatched(task_id: str):
from django.utils import timezone as tz
now = tz.now()
Task.objects.filter(task_id=task_id).update(
status=TaskStatus.DISPATCHED.value,
updated_at=now,
)
return now
@staticmethod
@sync_to_async
def _mark_dispatch_failed(task_id: str, error: str):
from django.utils import timezone as tz
now = tz.now()
Task.objects.filter(task_id=task_id).update(
status=TaskStatus.FAILED.value,
error=error,
updated_at=now,
)
return now
def create_task(self, req: TaskCreate) -> Task:
"""
创建任务记录:
@@ -131,20 +157,15 @@ class TaskDispatcher:
)
try:
await ws_send(msg)
from django.utils import timezone as tz
task.status = TaskStatus.DISPATCHED.value
task.updated_at = tz.now()
task.save(update_fields=["status", "updated_at"])
task.error = None
task.updated_at = await self._mark_dispatched(task.task_id)
logger.info("任务 %s 已派发", task.task_id)
return True
except Exception as e:
from django.utils import timezone as tz
task.status = TaskStatus.FAILED.value
task.error = f"派发失败: {e}"
task.updated_at = tz.now()
task.save(update_fields=["status", "error", "updated_at"])
task.updated_at = await self._mark_dispatch_failed(task.task_id, task.error)
logger.error("任务 %s 派发失败: %s", task.task_id, e)
return False