简体   繁体   中英

How to use async function inside celery task?

I've found some similar questions but couldn't find what I want.
I have async function which is I want to use it inside my celery task but cannot call it with await inside task. Is there any way to do it?

db.py

async def select_users():
    sql = "SELECT * FROM Users WHERE "
    sql, parameters = self.format_args(sql, parameters=kwargs)
    return await self.execute(sql, *parameters, fetchrow=True)

tasks.py

from .celery import app
import db

@app.task
def update_credits():
    users = db.select_users()  #here I should call func with 'await'
    print(users)

You can use the Event Loop method run_until_complete :

import asyncio
from .celery import app
import db

@app.task
def update_credits():
    loop = asyncio.get_event_loop()
    users = loop.run_until_complete(db.select_users())
    print(users)

But if you do not await the db.select_users() coroutine inside an async def your code is not getting any improve by using asyncio .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM