Skip to content

Instantly share code, notes, and snippets.

@pangyuteng
Last active May 3, 2026 19:21
Show Gist options
  • Select an option

  • Save pangyuteng/3b37154cf8a7f21321c3d072caecfb3e to your computer and use it in GitHub Desktop.

Select an option

Save pangyuteng/3b37154cf8a7f21321c3d072caecfb3e to your computer and use it in GitHub Desktop.
celery task running asyncio funcs

"async_to_sync turns an awaitable into a synchronous callable, and asyncio.run executes a coroutine and return the result."

#note: maybe needs to tweak worker --pool options solo prefork gevent

ref

https://stackoverflow.com/questions/59503825/django-async-to-sync-vs-asyncio-run

https://stackoverflow.com/questions/39815771/how-to-combine-celery-with-asyncio/54373183#54373183

import asyncio
from asgiref.sync import async_to_sync

from celery import Celery

app = Celery('tasks')

async def return_hello(param1, param2):
    await asyncio.sleep(1)
    return 'hello'

@app.task()
def foo(param1, param2):
    asyncio.run(return_hello(param1, param2))

@app.task()
def baz(param1, param2):
    loop = asyncio.new_event_loop()
    loop.run_until_complete(return_hello(param1, param2))
    loop.close()

@app.task()
def bar(param1, param2):
    async_to_sync(return_hello)(param1, param2)


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment