Concept Explanation
In AsyncIO, a Coroutine is just a function that could run asynchronously. A Task is that function actually running in the background.
Think of it like this:
- Coroutine: A recipe for a cake.
- Task: Putting the cake in the oven.
Once you wrap a coroutine in a Task, it is handed over to the Event Loop. The loop will start running it as soon as possible. This allows you to start many tasks and then go do something else while they "cook" in the background.
Syntax or Core Structure
Creating Tasks
The standard way to create a task is asyncio.create_task(coroutine).
import asyncio
async def my_routine():
await asyncio.sleep(1)
return "Result"
async def main():
# Task starts immediately in the background
task = asyncio.create_task(my_routine())
# We can do other things here
print("Task is running...")
# Eventually, we 'await' the task to get its result
value = await task
print(f"Goal: {value}")
asyncio.run(main())
Code Example #1 (Basic)
Canceling a task that is taking too long.
import asyncio
async def long_running_task():
try:
print("Working hard...")
await asyncio.sleep(10)
print("Finished!")
except asyncio.CancelledError:
print("Cleanly shutting down after cancel...")
async def main():
task = asyncio.create_task(long_running_task())
await asyncio.sleep(2)
print("Giving up! Canceling...")
task.cancel() # Stop the task
await asyncio.sleep(1) # Let the cleanup happen
asyncio.run(main())
Code Example #2 (Intermediate)
Handling timeouts with asyncio.wait_for().
import asyncio
async def slow_api():
await asyncio.sleep(5)
return "Final Data"
async def main():
print("Fetching data with a 2-second limit...")
try:
# If the task isn't done in 2s, it raises a TimeoutError
result = await asyncio.wait_for(slow_api(), timeout=2.0)
print(result)
except asyncio.TimeoutError:
print("The request timed out!")
asyncio.run(main())
Real World Example
Background Image Uploader: Imagine a mobile app where the user clicks "Save" and can immediately keep using the app while the image uploads in the background.
import asyncio
async def upload_image(img_id):
print(f"📸 Uploading image {img_id}...")
await asyncio.sleep(3)
print(f"✅ Image {img_id} uploaded successfully!")
async def main():
print("User clicked 'Upload Profile Picture'")
# Start the upload in the background
asyncio.create_task(upload_image("p101"))
print("User is now editing their bio while the upload happens...")
await asyncio.sleep(1)
print("User clicked 'Save Bio'")
print("Finished work. Closing app soon.")
await asyncio.sleep(3) # Wait so we can see the upload finish
asyncio.run(main())
Common Mistakes
- Forgetting to Await: If you create a task but the main program finishes before the task does, the task will be killed instantly. Always make sure your tasks have enough time or are awaited.
- Circular Tasks: A task that creates another task that creates the first task will quickly crash your computer with infinite recursion.
- Task References: If you create a task but don't store it in a variable, Python's Garbage Collector might delete it before it even begins! Always use
t = asyncio.create_task(...).
Best Practices
- Clean Cancellation: Always use
try...except asyncio.CancelledErrorinside your tasks to close files or database connections if they get stopped. - Use Descriptive Names: In Python 3.8+, you can name your tasks:
asyncio.create_task(..., name="EmailUploader"). This makes debugging much easier. - Wait for completion: Use
asyncio.gather()orasyncio.wait()if you need to be sure a group of tasks is completely finished.
Practice Exercises
- The Canceler: Write a task that prints "Tick" every second. Write a main function that lets it run for 4 seconds and then cancels it.
- Timeout Master: Create a task that takes between 1 and 5 seconds (randomly). Use
wait_forwith a 3-second limit and print if it succeeded or died. - Background Logger: Write a background task that logs "System OK" to the terminal every 2 seconds while the main program waits for user input.