编写和调用 @shared_task
使用 delay() 异步运行函数
编写和调用 @shared_task 是 CoddyKit 上的免费 Django Academy 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Django Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Django Academy 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Tasks Are Just Functions
A Celery task is an ordinary Python function with a decorator on top. The decorator teaches Celery how to queue and run it later.
Why shared_task
Use @shared_task instead of @app.task so your tasks do not depend on a specific Celery app. It is the standard choice inside Django apps.
Write Your First Task
Put tasks in a tasks.py inside an app. Decorate a plain function and Celery picks it up via autodiscover.
from celery import shared_task
@shared_task
def add(x, y):
return x + yCall It with delay
To run a task in the background, call .delay() instead of calling the function directly. It queues the job and returns at once.
add.delay(2, 3) # queued, runs on a workerdelay vs Calling Directly
Calling add(2, 3) runs it right now in your web process. Calling add.delay(2, 3) sends it to the queue. Same function, very different timing.
Pass Simple Arguments
Arguments are serialized to JSON and sent to the broker, so pass simple values like IDs and strings, not whole model objects.
send_email.delay(user.id) # good
send_email.delay(user) # avoid: not serializableThe AsyncResult Handle
delay() returns an AsyncResult. You can store its id and later check status or fetch the return value from the result backend.
result = add.delay(2, 3)
print(result.id)More Control with apply_async
Need a countdown or a specific queue? Use apply_async(), the fuller version of delay with extra options.
add.apply_async((2, 3), countdown=10) # run after 10sRetry on Failure
Bind a task and call self.retry() to re-run it after an error, perfect for flaky network calls that may succeed next time.
@shared_task(bind=True, max_retries=3)
def fetch(self):
try:
call_api()
except Exception as e:
raise self.retry(exc=e)Idempotent Tasks Win
Because tasks can retry, aim to make them idempotent: running twice should be safe and not double-charge or double-send. 🔁
Watch the Worker Log
When you call delay, watch the worker terminal. You will see the task received and its result, which is the fastest way to debug. 👀
Quick Check
How do you run a Celery task in the background?
Recap: Writing Tasks
Decorate a function with @shared_task, call it with .delay() to queue it, pass simple ids, and design tasks to retry safely. 🎯
常见问题解答
「编写和调用 @shared_task」课时是免费的吗?
是的 — 「编写和调用 @shared_task」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Django Academy 课程的其余内容,请升级到 CoddyKit PRO。 Django Academy 课程共包含 4 节课。
「编写和调用 @shared_task」这节课中我会学到什么?
使用 delay() 异步运行函数 你通过在浏览器中直接运行的动手代码来练习 Django Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Django Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Django Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。
「编写和调用 @shared_task」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Django Academy 课中编写并运行代码吗?
能。每节 Django Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 为什么需要后台任务
- 使用代理设置 Celery
- 编写和调用 @shared_task
- 使用 Celery Beat 调度任务