# Created on savesnippets.com · https://savesnippets.com/DZpSMLVGiNtbpV import asyncio async def slow_task(): await asyncio.sleep(5) return "done" async def main(): try: result = await asyncio.wait_for(slow_task(), timeout=2.0) print(result) except asyncio.TimeoutError: print("Gave up after 2 seconds") # Python 3.11+ alternative — context manager form, slightly more flexible: async def main_modern(): try: async with asyncio.timeout(2.0): await slow_task() except TimeoutError: print("Gave up after 2 seconds") asyncio.run(main())