Три способа выполнить множество задач с asyncio
Функция для примера:
async def do_it(n):
await asyncio.sleep(random.uniform(0.5, 1))
return n
1. Последовательный вызов
async def main():
for i in range(100):
result = await do_it(i)
Такой вызов имеет смысл только тогда, когда результат одной задачи требуется для вызова следующей.
Если они независимы, то это антипаттерн, так как аналогичен простому синхронному вызову по очереди.
2. Упорядоченный результат
async def main():
tasks = [do_it(i) for i in range(100)]
results = await asyncio.gather(*tasks)
Выполняет корутины конкурентно и возвращает результат в виде списка.
Полезен когда требуется получить результаты в том же порядке в котором задачи отправлены.
3. Результат по мере готовности
tasks = [asyncio.create_task(do_it(i)) for i in range(100)]
for cor in asyncio.as_completed(tasks):
result = await cor
Так же выполняет корутины конкурентно, но не гарантирует порядок. Результат возвращается по мере готовности, каждый отдельно.
Полезен когда нужно обработать любой ответ как можно скорее.
#async
🌊 Bali authorities warn of high tides
🌤 Bali's Meteorology, Climate and Geophysics Agency is warning of extreme weather conditions for several days. In particular, of extremely high tides on the southern coast of the island.
❌ The population and tourists are advised to temporarily refrain from bathing on the beach of Kuta.
@BaliNews
#weather#tides#Kuta
🌎 In Australia’s Kimberley region, the Horizontal Falls are created when huge tidal currents force seawater through narrow rock gorges, producing powerful, temporary waterfalls that appear to flow sideways. Tides here can rise over 10 meters, creating one of the world’s most unusual tidal phenomena. ✨
#tides⚡#waterfalls⚡#Australia
👉subscribe Interesting Planet
🌍 Earth’s tides are driven mostly by the Moon’s gravity, causing oceans to rise and fall all over the globe. These constant movements help mix ocean waters and shape coastal ecosystems. ✨
#tides⚡#ocean⚡#cycles⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 The Wadden Sea along Europe’s North Sea coast is the world’s largest tidal mudflat system. Twice daily, the sea retreats for kilometers, revealing vast sandbanks and rich habitats for millions of migratory birds. ✨
#coastline⚡#tides⚡#wildlife⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 The Bay of Fundy in eastern Canada experiences the highest tidal range on Earth—up to 16 meters between high and low tide. These extreme tides carve dramatic coastal cliffs and ever-changing mudflats. ✨
#tides⚡#coast⚡#landscape⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels