I think I found what I want. I need to do the following:
import asyncio
async def long_task():
try:
async with asyncio.timeout(5):
print("Long task started")
await asyncio.sleep(10) # Simulate a long operation
return "Long task completed"
except asyncio.TimeoutError:
# Do something when you reached timout
except asyncio.CancelledError:
print("Long task cancelled")
raise
async def main():
background_task = asyncio.create_task(long_task())
# Do useful work
asyncio.run(main())