Skip to content

Instantly share code, notes, and snippets.

@kissgyorgy
Last active January 10, 2022 21:25
Show Gist options
  • Save kissgyorgy/ee07f59ed19886e7f473a99222f9a683 to your computer and use it in GitHub Desktop.
Save kissgyorgy/ee07f59ed19886e7f473a99222f9a683 to your computer and use it in GitHub Desktop.
Python: Handle cancellation in an asyncio background task
import asyncio
import httpx
async def infinite_loop(backend_client):
while True:
try:
await asyncio.sleep(3)
except asyncio.CancelledError:
print("Cancelled")
await backend_client.aclose()
break
try:
asyncio.run(infinite_loop(httpx.AsyncClient()))
except KeyboardInterrupt:
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment