Created
February 8, 2020 11:16
-
-
Save maatthc/b3658b64b36a53c783f6acd7522d2f3e to your computer and use it in GitHub Desktop.
Running asynchronous functions (coroutines) with Python 3 - similarly with JavaScript Promise.all
This file contains 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 | |
loop = asyncio.get_event_loop() | |
async def execute_task(): | |
time_out = random.uniform(0.5, 5) | |
print("Starting {:1.2f}..".format(time_out)) | |
await asyncio.sleep(time_out) | |
print("Stoping {:1.2f}..".format(time_out)) | |
return time_out | |
async def main(): | |
tasks = [] | |
for i in range(10): | |
tasks.append(asyncio.ensure_future(execute_task())) | |
results = await asyncio.gather(*tasks) | |
print(f"Results: {results}") | |
results = loop.run_until_complete(main()) | |
loop.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment