Python asyncio Advanced

Advanced loop management, low-level scheduling, and platform-aware asyncio usage.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all

Event Loop Management

Work with the running loop and low-level scheduling APIs.

Schedule a callback later

Run a plain callback after a delay.

pythonANYcall-latercallbackloop
python
import asyncio

def on_timer():
    print("timer fired")

async def main():
    loop = asyncio.get_running_loop()
    loop.call_later(0.2, on_timer)
    await asyncio.sleep(0.3)

asyncio.run(main())
Notes

For plain callbacks rather than coroutines, use loop scheduling methods.

Schedule from another thread

Use `call_soon_threadsafe()` when another thread must notify the loop.

pythonANYthreadsafecall-soonthreads
python
import asyncio
import threading

async def main():
    loop = asyncio.get_running_loop()
    event = asyncio.Event()

    def notify():
        loop.call_soon_threadsafe(event.set)

    threading.Thread(target=notify).start()
    await event.wait()
    print("notified")

asyncio.run(main())
Notes

This is the thread-safe callback bridge into the event loop.

Submit a coroutine from another thread

Use `run_coroutine_threadsafe()` with a loop reference.

pythonANYrun-coroutine-threadsafethreadsinterop
python
import asyncio
import threading

async def echo():
    return "ok"

async def main():
    loop = asyncio.get_running_loop()
    result_holder = {}

    def worker():
        future = asyncio.run_coroutine_threadsafe(echo(), loop)
        result_holder["value"] = future.result()

    t = threading.Thread(target=worker)
    t.start()
    await asyncio.sleep(0.1)
    t.join()
    print(result_holder["value"])

asyncio.run(main())
Notes

Useful when integrating threaded code with an existing event loop.

Migration and Platform Notes

Modern patterns and common platform limitations.

Prefer `get_running_loop()` in async code

Modern replacement for older loop access patterns.

pythonANYget-running-loopmodernmigration
python
import asyncio

async def main():
    loop = asyncio.get_running_loop()
    print(loop)

asyncio.run(main())
Notes

In modern async code, prefer `get_running_loop()` over relying on policy-driven implicit loop creation.

Know the file I/O caveat

Document the limitation around file descriptor watching for ordinary file I/O.

pythonANYplatformfile-iocaveat
python
# asyncio can monitor sockets and many OS handles, but regular file I/O
# is not made non-blocking just by using asyncio. Use threads or subprocesses
# for blocking file operations when needed.
Notes

Asyncio is primarily designed for network I/O and subprocess orchestration; ordinary file reads and writes can still block.

Recommended next

No recommendations yet.