需要:有一个函数用了async def语法,现在需要放入celery运行,这个函数用了aioredis和tortoise-orm,改回同步方法的话,工作量很大,如果能直接在celery中运行它,那就简单很多。解决方案如下:
import asyncio
from celery import Celery
app = Celery(__name__)
def run_async(coro):
return asyncio.run(coro)
@app.task
def do_sth(*args, **kwargs):
return run_async(_do_sth(*args, **kwargs))
# 注:一个task里面只能运行一次run_async
async def _do_sth(*args, **kwargs):
await sub_task()
return 'done.'
async def sub_task():
...
# Call task
def demo_to_call_task():
args, kwargs = (), {}
task = do_sth.delay(*args, **kwargs)
return {'task_id': task.id}
Note: Celery官方要到5.0才支持asyncio