Files
live-campus-mcs-p-2027.2/Semaine_09/Asyncio_examples/exo_03.py
T
gauvainboiche ce1f0e513a feat: Semaine 9
2026-05-15 16:24:56 +02:00

34 lines
966 B
Python

# exo 3
import asyncio
SERVEURS = {
"serveur_A": 0.5,
"serveur_B": 2.0,
"serveur_C": 5.0,
"serveur_D": 1.2,
}
async def interroger(nom, delai):
await asyncio.sleep(delai)
return f"réponse de {nom}"
async def appel_avec_timeout(nom, delai, timeout=2.0):
try:
resultat = await asyncio.wait_for(interroger(nom, delai), timeout=timeout)
print(f"{nom} : {resultat}")
return nom, True
except asyncio.TimeoutError:
print(f"{nom} : timeout après {timeout}s")
return nom, False
async def main():
taches = [appel_avec_timeout(nom, delai) for nom, delai in SERVEURS.items()]
resultats = await asyncio.gather(*taches)
ok = [n for n, success in resultats if success]
ko = [n for n, success in resultats if not success]
print("\n--- Résumé ---")
print(f"En ligne ({len(ok)}) : {', '.join(ok)}")
print(f"Timeout ({len(ko)}) : {', '.join(ko)}")
asyncio.run(main())