41 lines
1.2 KiB
Python
41 lines
1.2 KiB
Python
# exo 5
|
|
import asyncio
|
|
import time
|
|
|
|
SERVICES = [
|
|
{"nom": "base de données", "delai": 0.3},
|
|
{"nom": "cache Redis", "delai": 0.1},
|
|
{"nom": "API externe", "delai": 3.5},
|
|
{"nom": "serveur mail", "delai": 0.8},
|
|
{"nom": "CDN", "delai": 1.5},
|
|
]
|
|
TIMEOUT = 2.0
|
|
|
|
async def check(service):
|
|
nom, delai = service["nom"], service["delai"]
|
|
debut = time.time()
|
|
try:
|
|
await asyncio.wait_for(asyncio.sleep(delai), timeout=TIMEOUT)
|
|
return nom, True, time.time() - debut
|
|
except asyncio.TimeoutError:
|
|
return nom, False, TIMEOUT
|
|
|
|
async def main():
|
|
start = time.time()
|
|
taches = [asyncio.create_task(check(s)) for s in SERVICES]
|
|
|
|
en_ligne, hors_ligne = 0, 0
|
|
for tache in asyncio.as_completed(taches):
|
|
nom, ok, duree = await tache
|
|
if ok:
|
|
print(f"✓ {nom:<20} EN LIGNE ({duree:.2f}s)")
|
|
en_ligne += 1
|
|
else:
|
|
print(f"✗ {nom:<20} HORS LIGNE (timeout {duree:.1f}s)")
|
|
hors_ligne += 1
|
|
|
|
total = time.time() - start
|
|
print(f"\nRésumé : {en_ligne} en ligne, {hors_ligne} hors ligne — temps total {total:.2f}s")
|
|
|
|
if __name__ == "__main__":
|
|
asyncio.run(main()) |