Tugas Latar Belakang dan Antrean Pekerjaan
Pelajari cara memindahkan pekerjaan lambat dari pengendali permintaan menggunakan tugas latar belakang FastAPI dan antrean pekerjaan terdistribusi seperti Celery.
Tugas Latar Belakang dan Antrean Pekerjaan adalah pelajaran FastAPI Backend Development Bootcamp gratis di CoddyKit. Ini adalah pelajaran 4 dari 4. Kamu bisa membaca pelajaran lengkapnya di bawah secara gratis — lalu praktikkan langsung di browser dengan editor kode bawaan dan tutor AI 24/7. Ini adalah bagian dari jalur belajar FastAPI Backend Development Bootcamp, dan progresmu tersinkronisasi di web dan aplikasi CoddyKit. Kursus FastAPI Backend Development Bootcamp mencakup 4 pelajaran total.
Bagian dari pelajaran ini belum diterjemahkan dan ditampilkan dalam bahasa Inggris.
Why Offload Work?
Some work, like sending email, generating reports, or processing images, is too slow to do inside a request.
Making the user wait hurts latency. Instead, respond fast and do the heavy work in the background.
FastAPI BackgroundTasks
FastAPI ships a lightweight BackgroundTasks tool for work that should run after the response is sent.
from fastapi import BackgroundTasks
def write_log(msg: str):
with open("log.txt", "a") as f:
f.write(msg)
@app.post("/signup")
def signup(bg: BackgroundTasks):
bg.add_task(write_log, "new user")
return {"ok": True}Limits of BackgroundTasks
BackgroundTasks runs in the same process. If the server restarts, the work is lost, and it cannot scale across machines.
For durable, distributed work you need a real job queue.
What is a Job Queue?
A job queue stores tasks in a broker such as Redis or RabbitMQ. Separate worker processes pull tasks and execute them, independent of the web server.
Defining a Celery Task
Celery is the most common Python job queue. You decorate a function as a task.
from celery import Celery
celery_app = Celery("tasks", broker="redis://localhost:6379/0")
@celery_app.task
def send_email(to: str):
# slow work here
return "sent to " + toEnqueuing from FastAPI
Trigger the task with .delay(); it returns immediately while a worker runs it later.
@app.post("/notify")
def notify(email: str):
send_email.delay(email)
return {"queued": True}Running Workers
Workers are separate processes you scale independently of the web tier.
celery -A tasks worker --loglevel=info --concurrency=4Tracking Task Results
With a result backend, you can store and query task status and outcomes.
result = send_email.delay("a@b.com")
print(result.id, result.status)Retries and Reliability
Job queues can automatically retry failed tasks with backoff, something in-process tasks cannot do.
@celery_app.task(bind=True, max_retries=3)
def process(self, item):
try:
do_work(item)
except Exception as exc:
raise self.retry(exc=exc, countdown=10)Scheduling Periodic Jobs
Celery Beat runs tasks on a schedule, like nightly cleanups or hourly syncs.
celery_app.conf.beat_schedule = {
"cleanup": {"task": "tasks.cleanup", "schedule": 3600.0}
}Idempotent Tasks
Because a queued task may be retried, design tasks to be idempotent so running them twice causes no harm, for example by checking if the email was already sent.
Quick Check
Test your background work knowledge.
Recap
You learned to keep request handlers fast:
- BackgroundTasks handles simple in-process after-response work
- Job queues like Celery give durable, distributed, retryable tasks
- Scale workers independently and schedule periodic jobs
Offloading slow work keeps your API responsive under load.
Pertanyaan yang Sering Diajukan
Apakah pelajaran “Tugas Latar Belakang dan Antrean Pekerjaan” gratis?
Ya — teks lengkap “Tugas Latar Belakang dan Antrean Pekerjaan” gratis dibaca di sini di web. Untuk praktiknya secara interaktif (editor kode bawaan dan tutor AI 24/7) dan buka sisa kursus FastAPI Backend Development Bootcamp, upgrade ke CoddyKit PRO. Kursus FastAPI Backend Development Bootcamp mencakup 4 pelajaran total.
Apa yang akan aku pelajari di “Tugas Latar Belakang dan Antrean Pekerjaan”?
Pelajari cara memindahkan pekerjaan lambat dari pengendali permintaan menggunakan tugas latar belakang FastAPI dan antrean pekerjaan terdistribusi seperti Celery. Kamu berlatih FastAPI Backend Development Bootcamp dengan kode praktik yang langsung kamu jalankan di browser, dan tutor AI 24/7 menjawab pertanyaanmu saat kamu mengerjakan pelajaran ini.
Apakah aku perlu pengalaman untuk memulai FastAPI Backend Development Bootcamp?
Tidak diperlukan pengalaman sebelumnya. FastAPI Backend Development Bootcamp di CoddyKit dirancang untuk pemula hingga pelajar tingkat lanjut, jadi kamu bisa memulai di sini atau dari awal dan belajar sesuai kecepatan kamu sendiri. Ini adalah pelajaran 4 dari 4.
Berapa lama pelajaran “Tugas Latar Belakang dan Antrean Pekerjaan” memakan waktu?
Sebagian besar pelajaran CoddyKit memakan waktu sekitar 5–10 menit. Setiap pelajaran ringkas dan interaktif, jadi kamu membuat kemajuan stabil dan melanjutkan dari tempat kamu tinggalkan di web dan aplikasi.
Bisakah aku menulis dan menjalankan kode dalam pelajaran FastAPI Backend Development Bootcamp ini?
Ya. Setiap pelajaran FastAPI Backend Development Bootcamp menyertakan editor kode bawaan, jadi kamu menulis dan menjalankan kode nyata langsung di browser dan mendapatkan umpan balik AI instan — tidak diperlukan penyiapan lokal.
Semua pelajaran dalam kursus ini
- Strategi Caching dengan Redis
- Akses Basis Data Asinkron
- Penyeimbangan Beban dan Pemantauan
- Tugas Latar Belakang dan Antrean Pekerjaan