Created
January 7, 2022 10:04
-
-
Save narenaryan/4e926a4f0e65815ee1aac7ea3055abda to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import asyncio | |
| import random | |
| # A co-routine | |
| async def add(x: int, y: int): | |
| # function can do work between 1 second to 5 seconds | |
| await asyncio.sleep(random.randrange(1, 5)) | |
| return x + y | |
| # Create a function to schedule co-routines on the event loop | |
| # then print results | |
| async def get_results(): | |
| result = None | |
| try: | |
| # Wait for 3 seconds for co-routine to execute | |
| result = await asyncio.wait_for(add(3, 4), timeout=3) | |
| except asyncio.exceptions.TimeoutError: | |
| result = "fallback payload" | |
| print(result) | |
| asyncio.run(get_results()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment