Skip to content

Instantly share code, notes, and snippets.

@dmanchon
Created August 17, 2017 00:32
Show Gist options
  • Save dmanchon/15b052e4817ac187f80d9e6bb50532a5 to your computer and use it in GitHub Desktop.
Save dmanchon/15b052e4817ac187f80d9e6bb50532a5 to your computer and use it in GitHub Desktop.
Test ensure future asyncio
import asyncio
import concurrent.futures
import functools
import random
import time
import uuid
async def func(_id):
delay = random.randint(1, 20)
await asyncio.sleep(delay)
if delay % 7 == 0:
raise Exception(f'Failed {_id} with {delay}')
return _id, delay
def cb(fut):
try:
_id, delay = fut.result()
print(f'Finished {_id} after {delay}.')
except Exception as e:
print(e)
async def do():
tasks = []
loop = asyncio.get_event_loop()
for i in range(25):
_id = uuid.uuid4().hex
future = asyncio.ensure_future(func(_id))
future.add_done_callback(cb)
tasks.append(future)
print(f'Created {_id}...')
await asyncio.sleep(5)
print('Gathering...')
res = await asyncio.gather(*tasks, return_exceptions=True)
def main():
loop = asyncio.get_event_loop()
loop.run_until_complete(do())
loop.close()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment