定义并调用任务
编写任务并使用 delay 分发
定义并调用任务 是 CoddyKit 上的免费 Flask Academy 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Flask Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Flask Academy 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
What a Task Is
A Celery task is just a Python function marked so workers can run it later. You decorate it once and it becomes enqueueable.
The task Decorator
Mark a function with the Celery task decorator. Now it has extra methods like delay that schedule it onto the queue.
@celery.task
def add(x, y):
return x + yCall It Normally vs Queued
Calling add(2, 3) runs it right now in your process. To run it on a worker instead, you call its delay method.
Enqueue with delay
The delay shortcut puts the job on the broker and returns immediately. The work happens later on a worker.
add.delay(2, 3)apply_async for Options
Need more control like a countdown or queue name? Use apply_async, which takes args plus scheduling options.
add.apply_async(args=[2, 3], countdown=10)You Get an AsyncResult
Both delay and apply_async return an AsyncResult. It carries the task id you use to look up the result later.
job = add.delay(2, 3)
print(job.id)Arguments Must Serialize
Task arguments travel through the broker, so they must be serializable: use plain data like ints, strings, lists, and dicts.
Pass IDs, Not Objects
Do not send a database row to a task. Send its id instead, then re-fetch the object inside the task with a fresh session.
Enqueue Inside a View
A view validates input, enqueues the job, and returns a fast response. The user is not kept waiting for the slow part.
@app.post("/report")
def report():
add.delay(2, 3)
return {"status": "queued"}Name Tasks Clearly
Give tasks descriptive names like send_welcome_email. Clear names make logs and the broker dashboard far easier to read. 🔍
Keep Tasks Small
A good task does one clear job. Small, focused tasks are easier to retry, monitor, and reason about when something breaks.
Quick Check
You want a function to run on a worker.
Recap
Decorate a function as a task, call delay or apply_async to queue it, pass serializable args, and enqueue from thin views. ✅
常见问题解答
「定义并调用任务」课时是免费的吗?
是的 — 「定义并调用任务」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Flask Academy 课程的其余内容,请升级到 CoddyKit PRO。 Flask Academy 课程共包含 4 节课。
「定义并调用任务」这节课中我会学到什么?
编写任务并使用 delay 分发 你通过在浏览器中直接运行的动手代码来练习 Flask Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Flask Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Flask Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。
「定义并调用任务」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Flask Academy 课中编写并运行代码吗?
能。每节 Flask Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。