Функция 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
😄Account
➖➖➖➖➖➖
🔘An account is a record. We often use it to talk about recording money. If a bank looks after your money, you have an account with them. The arrangement that a business has with a client can also be called an account.
🔜You should put that money in a saving account.
🔜I'm responsible for the company's biggest account.
🔘An account can also be a description of something that happened, or a story.
🔜The police wanted to hear his account of what happened.
🔘We also use account in some common expressions. If you take something into account, then you consider it and if you account for something you explain why it happened.
🔜You'll need to take many factors into account to make this decision.
🔜We need you to account for your behaviour.
#Account👨🏫@America
➖➖➖➖➖➖➖➖➖➖➖➖
🆕 Crypto News @Money
😁 Crypto Game @Egame
🇺🇸 US News @America
🇯🇵 Japan News @Japan
🇦🇪 UAE News @Dubai
▶️ Popular Movies @Videos
😜 Best Funny Video @Funnys
@creationdatebot
Qué puede hacer este bot?
Este bot interpola las fechas de creación de cuentas basadas en ID de telegrama dado
Idioma: Inglés, Español, Ruso, uzbeco, Polaco, Árabe
(visto en @BotsGram_cu)
#account, #creationdate, #ids
@CheckRestrictionsBot
Qué puede hacer este bot?
Te ayudaré a saber qué restricciones tienen tus bots, grupos o canales.
Idioma: Inglés
(visto en @BotsGram_cu)
#restrict, #restrict, #restriction, #account, #check, #telegram, #private, #channels
@getaltsbot
Qué puede hacer este bot?
Este bot le permite alquilar números reales de teléfono por un período de 20 minutos para registrar cuentas de Telegram, Google, WhatsApp.
Idioma: Inglés
(visto en @BotsGram_cu)
#alt, #account, #phonenumber, #paid, #buy, #identity, #telegram
@pwned_robot
Qué puede hacer este bot?
Telegram Bot que puede comprobar si tiene una cuenta o contraseña que se ha visto comprometida en una violación de datos. Uso limitado (se pagan pocas opciones).
Idioma: Inglés
(visto en @BotsGram_cu)
#breach, #security, #hack, #password, #account, #compromised, #pwned, #checkpsw, #paste, #paid