[Python] Why is my asyncio task not executing immediately after `asyncio.create_task()`?

Discussão em 'Python' iniciado por Stack, Abril 17, 2025.

  1. Stack

    Stack Membro Participativo

    import asyncio

    async def worker():
    print("worker start")
    await asyncio.sleep(1)
    print("worker done")

    async def main():
    # Schedule the coroutine
    asyncio.create_task(worker())
    # Give control back to the event loop for a moment
    await asyncio.sleep(0.1)
    print("main exiting")

    asyncio.run(main())


    Expected behavior

    I thought calling asyncio.create_task(worker()) would start worker() right away, so I expected to see:

    worker start
    main exiting
    worker done


    Actual behavior

    Instead, nothing from worker() is printed until after main() finishes:

    main exiting
    worker start
    worker done


    What I’ve tried

    • Increasing the await asyncio.sleep(0.1) delay
    • Replacing asyncio.create_task with await worker()
    • Running on Python 3.11 and 3.12 (same outcome)

    Questions

    1. Why doesn’t the task begin execution immediately after create_task()?
    2. Is there a recommended pattern to ensure the task gets a chance to run before main() exits (without awaiting it directly)?

    Environment

    • Python 3.12.2
    • macOS 14.4 (Sonoma)

    Any insights appreciated!

    Continue reading...

Compartilhe esta Página