How to handle timeouts in async functions?

98 views

How to handle timeouts in async functions?

How to handle timeouts in async functions?

solveurit24@gmail.com Changed status to publish February 13, 2025
0

Use asyncio.timedelta and asyncio.wait_for() to set timeouts.

import asyncio
from datetime import timedelta

async def slow_function():
    await asyncio.sleep(2)
    return "Done"

async def main():
    try:
        result = await asyncio.wait_for(slow_function(), timeout=timedelta(seconds=1))
        print(result)
    except asyncio.TimeoutError:
        print("Function timed out")

asyncio.run(main())  # Output: Function timed out

solveurit24@gmail.com Changed status to publish February 13, 2025
0
You are viewing 1 out of 1 answers, click here to view all answers.