search
HomeBackend DevelopmentPython TutorialLearn Python Celery and easily complete asynchronous tasks

Although modern web applications are faster and more convenient than ever, there are still many situations where heavy tasks need to be transferred to other parts of the system instead of working on the main thread.

Examples of these situations are as follows:

  • Periodic tasks – jobs that are scheduled to run at specific intervals. For example, daily, monthly report generation.
  • Third Party Tools - Applications should return responses to the user quickly, rather than waiting for other tasks to complete first. For example, send emails, notifications, communicate update progress to internal tools.
  • Long-running jobs – jobs that perform complex or resource-expensive work and for which the user needs to wait for the job to complete. For example. DAG workflows, Map-Reduce based tasks, long-running Spark jobs, etc.

So, how to deal with these situations? At this time, Celery comes in handy.

What is Celery?

Celery is an open source task queue implementation, often combined with Python-based web frameworks such as Flask and Django, to execute tasks asynchronously outside of the typical request-response cycle.

So, Celery is essentially a task queue based on distributed messaging. Execution units or tasks are executed simultaneously on one or more workers using multiprocessing, gevent or eventlets. These tasks can be executed synchronously (i.e., wait until ready) or asynchronously (i.e., in the background).

轻松完成异步任务,一文搞懂Python Celery

How does Celery work?

Celery is a distributed task queue based on the producer-consumer model.

Task Queue is a mechanism for distributing work across threads and machines. It is essentially a message intermediary between producers (web applications) and consumers (Celery workers).

Celery interacts through messages, and the broker acts as an intermediary between clients (producers) and workers (consumers). To start a task, the client pushes a message to the queue, and the broker delivers the message to the worker.

The Celery system can be composed of multiple workers and brokers, which provides the possibility of high availability and horizontal expansion.

In short, the Celery client is the producer, which adds new tasks to the queue through the message broker. Then, Celery workers also obtain new tasks from the queue through the message broker. Once processed, the results are stored in the results backend.

Working Example

The following example will use RedisMQ as the message broker.

Set up Redis

On the linux/macOS system, run the Redis server locally by executing the following command:

$ wget http://download.redis.io/redis-stable.tar.gz
$ tar xvzf redis-stable.tar.gz
$ rm redis-stable.tar.gz
$ cd redis-stable
$ make

After setting up Redis, run the Redis server by executing the following command:

$ redis-server

The server runs on the default port 6379.

Set up the application

First, set up the Python project locally.

Celery can be installed through standard tools such as pip or easy_install. Install Celery and Redis through the following command:

pip install celery redis==4.3.4

Now you need a Celery instance to run the application. Any task implemented by Celery starts with an instance, such as creating and managing tasks.

Create a file tasks.py in the project:

From celery import Celery

broker_url = 'redi://localhost:6379/0'

app = Celery('tasks',broker = broker_url)

@app.task
def add(x, y):
return x+y

A simple task add() is defined here to return the sum of two numbers.

Run Celery Worker

In the terminal, switch to the project location and run Celery worker with the following command:

$ celery -A tasks worker - loglevel=info

For more information about the Celery worker command line, you can use help:

$ celery worker - help

Calling tasks

In Celery, use the delay() method to call tasks.

Open another terminal window for the project and run the following command:

$ python

This will open the Python command line.

>> from tasks import add
>> add.delay(1,2)

This will return an AsyncResult instance, which can be used to check the status of the task, get its return value, wait for the task to complete, and also get exceptions and tracebacks on failure.

After running the add.delay() command, the task will be pushed to the queue and then acquired by the worker. This can be verified on the Celery worker terminal, where you can clearly see the task being received and then completed successfully.

The above is the detailed content of Learn Python Celery and easily complete asynchronous tasks. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:51CTO.COM. If there is any infringement, please contact admin@php.cn delete
How are arrays used in scientific computing with Python?How are arrays used in scientific computing with Python?Apr 25, 2025 am 12:28 AM

ArraysinPython,especiallyviaNumPy,arecrucialinscientificcomputingfortheirefficiencyandversatility.1)Theyareusedfornumericaloperations,dataanalysis,andmachinelearning.2)NumPy'simplementationinCensuresfasteroperationsthanPythonlists.3)Arraysenablequick

How do you handle different Python versions on the same system?How do you handle different Python versions on the same system?Apr 25, 2025 am 12:24 AM

You can manage different Python versions by using pyenv, venv and Anaconda. 1) Use pyenv to manage multiple Python versions: install pyenv, set global and local versions. 2) Use venv to create a virtual environment to isolate project dependencies. 3) Use Anaconda to manage Python versions in your data science project. 4) Keep the system Python for system-level tasks. Through these tools and strategies, you can effectively manage different versions of Python to ensure the smooth running of the project.

What are some advantages of using NumPy arrays over standard Python arrays?What are some advantages of using NumPy arrays over standard Python arrays?Apr 25, 2025 am 12:21 AM

NumPyarrayshaveseveraladvantagesoverstandardPythonarrays:1)TheyaremuchfasterduetoC-basedimplementation,2)Theyaremorememory-efficient,especiallywithlargedatasets,and3)Theyofferoptimized,vectorizedfunctionsformathematicalandstatisticaloperations,making

How does the homogenous nature of arrays affect performance?How does the homogenous nature of arrays affect performance?Apr 25, 2025 am 12:13 AM

The impact of homogeneity of arrays on performance is dual: 1) Homogeneity allows the compiler to optimize memory access and improve performance; 2) but limits type diversity, which may lead to inefficiency. In short, choosing the right data structure is crucial.

What are some best practices for writing executable Python scripts?What are some best practices for writing executable Python scripts?Apr 25, 2025 am 12:11 AM

TocraftexecutablePythonscripts,followthesebestpractices:1)Addashebangline(#!/usr/bin/envpython3)tomakethescriptexecutable.2)Setpermissionswithchmod xyour_script.py.3)Organizewithacleardocstringanduseifname=="__main__":formainfunctionality.4

How do NumPy arrays differ from the arrays created using the array module?How do NumPy arrays differ from the arrays created using the array module?Apr 24, 2025 pm 03:53 PM

NumPyarraysarebetterfornumericaloperationsandmulti-dimensionaldata,whilethearraymoduleissuitableforbasic,memory-efficientarrays.1)NumPyexcelsinperformanceandfunctionalityforlargedatasetsandcomplexoperations.2)Thearraymoduleismorememory-efficientandfa

How does the use of NumPy arrays compare to using the array module arrays in Python?How does the use of NumPy arrays compare to using the array module arrays in Python?Apr 24, 2025 pm 03:49 PM

NumPyarraysarebetterforheavynumericalcomputing,whilethearraymoduleismoresuitableformemory-constrainedprojectswithsimpledatatypes.1)NumPyarraysofferversatilityandperformanceforlargedatasetsandcomplexoperations.2)Thearraymoduleislightweightandmemory-ef

How does the ctypes module relate to arrays in Python?How does the ctypes module relate to arrays in Python?Apr 24, 2025 pm 03:45 PM

ctypesallowscreatingandmanipulatingC-stylearraysinPython.1)UsectypestointerfacewithClibrariesforperformance.2)CreateC-stylearraysfornumericalcomputations.3)PassarraystoCfunctionsforefficientoperations.However,becautiousofmemorymanagement,performanceo

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software