Celery Background Tasks

    Celery is a powerful task queue that can be used for simple background tasksas well as complex multi-stage programs and schedules. This guide will show youhow to configure Celery using Flask, but assumes you’ve already read theFirst Steps with Celeryguide in the Celery documentation.

    Celery is a separate Python package. Install it from PyPI using pip:

    The first thing you need is a Celery instance, this is called the celeryapplication. It serves the same purpose as the object in Flask, just for Celery. Since this instance is used as theentry-point for everything you want to do in Celery, like creating tasksand managing workers, it must be possible for other modules to import it.

    This is all that is necessary to properly integrate Celery with Flask:

    The function creates a new Celery object, configures it with the brokerfrom the application config, updates the rest of the Celery config fromthe Flask config and then creates a subclass of the task that wraps thetask execution in an application context.

    Let’s write a task that adds two numbers together and returns the result. Weconfigure Celery’s broker and backend to use Redis, create a application using the factor from above, and then use it to define the task.

    If you jumped in and already executed the above code you will bedisappointed to learn that .wait() will never actually return.That’s because you also need to run a Celery worker to receive and execute thetask.

    The string has to point to your application’s packageor module that creates the celery object.

    Now that the worker is running, will return the result once the taskis finished.