Asyncio python
From Teknologisk videncenter
For a primer see Yield python
asyncio.create example
await vs. asyncio.create()
import asyncio
import time
async def fetch_data(url):
# Simulate a long-running network request
await asyncio.sleep(2) # Wait for 2 seconds
print(f"Data fetched from {url}")
async def main():
task1 = asyncio.create_task(fetch_data("https://example.com"))
task2 = asyncio.create_task(fetch_data("https://another.example.com"))
await task1
await task2
if __name__ == "__main__":
asyncio.run(main())
asyncio.gather example
import asyncio
import aioping
import time
import datetime
hosts = ['127.0.0.1', 'www.bmw.de', '8.8.8.8', "www.mercantec.dk","www.tdc.dk","92.38.178.249","www.audi.de","www.renault.fr"]
async def do_ping(host, timeout):
print(f" - Pinging {host}")
try:
return await aioping.ping(host, timeout) * 1000, host
except TimeoutError:
return None, host
async def main():
t1 = time.time() # Timestamp start pings
jobs = [do_ping(host, timeout=2) for host in hosts]
print("Starting jobs:")
tasks = await asyncio.gather(*jobs)
print("Results are in:")
for task in tasks:
if task[0]: # Or: if time is not None:
print(f" - It took {task[0]} mS to ping {task[1]}")
else:
print(f"{task[1]} is not responding")
t2 = time.time() # Timestamp end pings
print("========================================")
print(f"It took {t2-t1} seconds")
print("========================================")
if __name__ == '__main__':
asyncio.run(main())