Asynchronous tasks
What is Asynchronous?
for ask the question:
there is anther question what is Synchronous?
In web project, we konw a method call ajax. ajax is a Asynchronous method. Its characteristics are: Once started, the method returns immediately and the calling place can continue to perform other functions.
So, Synchronous is completely opposite.
Synchronous, Once started, the method must waiting for returns, if not, the calling place can’t continue
if you can’t understand, here is a image to explan there different:
Need Asynchronous task in web project?
The anwser is Yes, we need.
Taking into account the user experience, when the user needs to register a mailbox, web must returns immediately, user can’t waiting 5-8s for the returns.
How to bulid and use Asynchronous task?
In Django project, we often use Celery:Distributed Task Queue
Asynchronous task consist of 3 parts
part1: Task initiation
part2: Task queue(broker)
part3: Task processing(worker)
Use Celery
First step: Build an Application
main.py
from celery import Celery
app = Celery(name='') # taskname
app.config_from_object('proj.celeryconfig')
app.autodiscover_tasks(['proj'])
proj.celeryconfig.py
BROKER_URL = 'redis://'
CELERY_RESULT_BACKEND = 'redis://'
proj.tasks
from main import app
@app.task(name)
def task1():
print("task1 is executing")
@app.task(name)
def task2():
print("task2 is executing")
....
start worker
celery -A proj worker -l info
本文解释了同步与异步任务的概念,并通过示例说明了异步任务的重要性,特别是在提高用户体验方面的作用。文章还介绍了如何在Django项目中使用Celery来实现异步任务。
2128

被折叠的 条评论
为什么被折叠?



