python_asyncio_course/6_tasks/6_03_4_task.py

59 lines
1.7 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import asyncio
import time
NETWORK_SPEED = 8
files = {
"file1.mp4": 32,
"image2.png": 24,
"audio3.mp3": 16,
"document4.pdf": 8,
"archive5.zip": 40,
"video6.mkv": 48,
"presentation7.pptx": 12,
"ebook8.pdf": 20,
"music9.mp3": 5,
"photo10.jpg": 7,
"script11.py": 3,
"database12.db": 36,
"archive13.rar": 15,
"document14.docx": 10,
"spreadsheet15.xls": 25,
"image16.gif": 2,
"audioBook17.mp3": 60,
"tutorial18.mp4": 45,
"code19.zip": 22,
"profile20.jpg": 9,
}
async def download_file(filename: str, size: int):
download_time = size / NETWORK_SPEED
print(
f"Начинается загрузка файла: {filename}, его размер {size} мб, время загрузки "
f"составит {download_time} сек"
)
await asyncio.sleep(download_time)
print(f"Загрузка завершена: {filename}")
async def monitor_tasks(tasks):
await asyncio.sleep(0.2)
while len(tasks) > 0:
done, tasks = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
for task in tasks:
print(f"Задача {task.get_name()}: в процессе, Статус задачи {task.done()}")
for task in done:
print(f"Задача {task.get_name()}: завершена, Статус задачи {task.done()}")
await asyncio.sleep(1)
async def main():
tasks = [
asyncio.create_task(download_file(filename, file_size), name=filename)
for filename, file_size in files.items()
]
await monitor_tasks(tasks)
print("Все файлы успешно загружены")
asyncio.run(main())