Files
fastapi_best_architecture/backend/app/task/tasks/base.py
Wu Clan ce3be1db8e Add support for celery dynamic tasks (#715)
* Add support for celery dynamic tasks

* Update the celery conf

* Update the celery task tables name

* Refactor the celery task-related interfaces

* Optimize auto-discovery tasks

* Remove redundant config

* Refine the business codes

* Optimize crontab validation returns

* Update dependencies in pyproject toml

* Fix some bugs

* Update dependencies

* Update the version to 1.7.0

* Fix update and delete event
2025-07-11 07:54:33 +08:00

49 lines
1.3 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import asyncio
from typing import Any
from celery import Task
from sqlalchemy.exc import SQLAlchemyError
from backend.common.socketio.actions import task_notification
from backend.core.conf import settings
class TaskBase(Task):
"""Celery 任务基类"""
autoretry_for = (SQLAlchemyError,)
max_retries = settings.CELERY_TASK_MAX_RETRIES
async def before_start(self, task_id: str, args, kwargs) -> None:
"""
任务开始前执行钩子
:param task_id: 任务 ID
:return:
"""
await task_notification(msg=f'任务 {task_id} 开始执行')
async def on_success(self, retval: Any, task_id: str, args, kwargs) -> None:
"""
任务成功后执行钩子
:param retval: 任务返回值
:param task_id: 任务 ID
:return:
"""
await task_notification(msg=f'任务 {task_id} 执行成功')
def on_failure(self, exc: Exception, task_id: str, args, kwargs, einfo) -> None:
"""
任务失败后执行钩子
:param exc: 异常对象
:param task_id: 任务 ID
:param einfo: 异常信息
:return:
"""
asyncio.create_task(task_notification(msg=f'任务 {task_id} 执行失败'))