Функция asyncio.wait() это еще один способ вызвать множество асинхронных задач.
Она работает в нескольких режимах.
1. Самый простой - ждем завершения всех задач
async def main():
tasks = [asyncio.create_task(do_it(i)) for i in range(10)]
done, pending = await asyncio.wait(
tasks,
return_when=asyncio.ALL_COMPLETED
)
for task in done:
try:
print(task.result())
except Exception as e:
print(e)
Очень похоже на gather, но работает не так.
▫️возвращает не результаты, а два сета с объектами Task у которых можно забрать результат через task.result() если они в списке done
▫️не гарантирует порядок результатов так как оба объекта это set
▫️не выбрасывает исключение когда оно появляется, а сохраняет его в Task. Исключение появится когда попробуете забрать резултьтат.
2. Ждем завершения первой задачи, даже если там ошибка.
async def main():
tasks = [asyncio.create_task(do_it(i)) for i in range(3)]
done, pending = await asyncio.wait(
tasks,
return_when=asyncio.FIRST_COMPLETED
)
# в done может быть несколько задач!
for task in done:
try:
print(task.result())
except Exception as e:
print(f"Fail: {e}")
# Оставшиеся задачи в pending, как правило, нужно отменить, иначе они будут продолжать работать
for task in pending:
task.cancel()
В сете done будут таски которые успели завершится, причем как успешно так и нет.
3. До первой ошибки.
Тоже самое, но с аргументом FIRST_EXCEPTION
done, pending = await asyncio.wait(
tasks,
return_when=asyncio.FIRST_EXCEPTION
)
Функция завершается как только первая задача упадет с ошибкой.
Учтите, что в любом случае done вы можете обранужить несколько задач, как с ошибками так и успешные.
↗️ Полный листинг примеров здесь
#async
Auto CPR First Aid Choking Device Outdoor Home Choking #Emergency Equipment Adults Children Breath Rescue Anti Suffocation Device
Buy link amazon 👇
https://amzn.to/40fuhzJ
Bay link Aliexpress 👇
https://s.click.aliexpress.com/e/_EIAiLBO
The US government has revealed a list of items Americans should keep on hand in case of an emergency.
Officials warned that households should be prepared to survive on their own for several days if disaster strikes, with no immediate access to outside help.
The Department of Homeland Security recommends storing enough water, food, and medical supplies to sustain every person in a household during an extended emergency.
At the top of the list is water, at least one gallon per person per day, along with several days' worth of non-perishable food. Americans are also urged to keep critical safety items such as flashlights, radios, batteries, and first-aid kits readily available in a portable emergency supply kit.
Officials said the supplies should be stored in airtight containers and kept in easy-to-carry bins or bags in case families need to evacuate quickly.
The checklist also includes tools to signal for help, sanitation supplies, and equipment to shelter safely indoors if conditions outside become dangerous.
While the Trump administration has not urged Americans to stockpile large quantities of supplies, federal officials and preparedness experts recommend keeping essential items on hand in case of an emergency.
#Security#Emergency
👂More on Trump's Ear ⚠️
On January 19, 1966, Indira Gandhi became India’s first female Prime Minister after Lal Bahadur Shastri died. She led the Green Revolution to increase food production and imposed the Emergency in 1975, limiting freedoms. Her time in office had major changes and controversies.
🌾🇮🇳
[Read more]
@googlefactss#IndiraGandhi#India#History#GreenRevolution#Emergency