pythonpython-3.xasynchronouscelerypython-asyncio

How to combine Celery with asyncio?


How can I create a wrapper that makes celery tasks look like asyncio.Task? Or is there a better way to integrate Celery with asyncio?

@asksol, the creator of Celery, said this::

It's quite common to use Celery as a distributed layer on top of async I/O frameworks (top tip: routing CPU-bound tasks to a prefork worker means they will not block your event loop).

But I could not find any code examples specifically for asyncio framework.


Solution

  • EDIT: 01/12/2021 previous answer (find it at the bottom) didn't age well therefore I added a combination of possible solutions that may satisfy those who still look on how to co-use asyncio and Celery

    Lets quickly break up the use cases first (more in-depth analysis here: asyncio and coroutines vs task queues):

    So it makes sense in the context of Python's "Do one thing and do it well" to not try and mix asyncio and celery together.

    BUT what happens in cases where we want to be able to run a method both asynchronously and as an async task? then we have some options to consider:

    Finally, there are some ready-made solutions, that I cannot recommend (because I have not used them myself) but I will list them here:


    Well that didn't age so well did it? Version 5.0 of Celery didn't implement asyncio compatibility thus we cannot know when and if this will ever be implemented... Leaving this here for response legacy reasons (as it was the answer at the time) and for comment continuation.

    That will be possible from Celery version 5.0 as stated on the official site:

    http://docs.celeryproject.org/en/4.0/whatsnew-4.0.html#preface

    1. The next major version of Celery will support Python 3.5 only, where we are planning to take advantage of the new asyncio library.
    2. Dropping support for Python 2 will enable us to remove massive amounts of compatibility code, and going with Python 3.5 allows us to take advantage of typing, async/await, asyncio, and similar concepts there’s no alternative for in older versions.

    The above was quoted from the previous link.

    So the best thing to do is wait for version 5.0 to be distributed!

    In the meantime, happy coding :)