Функция 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
We all are one.
The sun, the moon and the earth are one (once),
But in the time they all seperated,
Being and living far away,
But they all are one.
We born on different places,
We raised in different cities,
We studied in different institutions,
But we all are on one stage. i.e,, Life.
Our handwriting may be different
But the alphabet are one,
Pens may be different,
But the ink is same,
Books may be different,
But the knowledge is eternal.
We all are separated ,
by life,
by paths,
By careers,
But our hearts are together,
and We all are one.
Our tastes,
our preferences,
our perspectives,
our thinking,
May be different but,
We all are one.
S NAVEEN
#poetry#SN#review
Seperation lives
The life of human started from seperation,
Separation from the ocean,
Separation from the species, and
Separation from the womb of mother.
Nature is separated,
Oceans are separated,
Continents are separated, and so,
The nations emerged seperately.
Separation is the birth of new life,
Separation leads to innovation,
Separation is the worse, but
Separation is the nature.
When two persons seperates,
The heart brokes, and
Mind resides in despair, and
Life teaches the valuable lessons.
Even the origin of universe,
Started from the separation,
From one to one and another,
Separation is an unending process.
Separation begins with despair and,
End with hope.
Separation is natural and,
Separation is permanent.
PS: ignore grammatical mistakes
S NAVEEN
10-07-2022
#poetry#SN#review
Deadly hunger
I have seen that one person begged,
Other person insulted his fellow being,
And the other person cried for his condition.
I have seen people selling their body,
I have seen one died, and
Other inviting the death.
I have seen one in misery,
Other fighting to end the misery,
And other mentally broke down in it.
I have seen the starvation of children,
I have seen men working hard, and
The old seeking for help.
I have seen false promises of politicians,
Flop ideas of business men,
Which told to end hunger and poverty.
Hunger, a six letters word,
Running the world with ruthless,
Where it has no permanent end.
S NAVEEN
23-06-2022
#poetry#SN#review
These nights
I hope sleep find its way,
Before my thoughts destroy me,
Exhausted feelings and emotions will make,
These nights more scary.
There was a nights in moon light,
where we are sleeping peacefully,
Why this artificial lights making,
These nights more terrible.
In the war of mind and heart,
Sleep is just a pawn,
Where heart and mind will never win the war,but
These nights witness as spectators.
S NAVEEN
#poetry#SN#review
Sky...
You are the blue,
You are the light,
You are the carrier of clouds.
You have been witnessing the war,
You have been witnessing the peace,
You have been witnessing the love,
You have been witnessing the world. (From Alpha)
You have seen the tragedy,
You have seen the lives,
You have seen the nature,
You are the meaning of eternal.
You took the poison,
You took the pollution,
Yet, you never changed your colour. (like politicians)
You are the miniature of the oceans.
You are the floating blue ocean and
wonder of the universe.
S NAVEEN
#poetry#SN#review
On Long distance relationship.
Distance is just a word,
When two hearts beat together,
Kilometres and miles are just measurements,
When two souls turns into one.
There may be lack of communication,
But two minds will think the same.
Distance and lack of communication is;
Just for those, who thinks they are separate,
Not for those, who thinks they are together.
Love never thinks it way in impossibilities,
It always find it ways in possibilities.
S. NAVEEN
#poetry#SN#review
Eternal Love
I just opened the eyes,
Aloud tears filled the room,
That's the first time that,
I saw true form of love,
My Mother.
She hugged and kissed me,
With happiness and tears in her eyes,
That's the selfless love.
I have never seen 'her' before,
But I felt her touch in womb,
Her hands touched me,
Her womb protected me.
I have seen her and cried,
Her gentleness in heart,
Her intangible love,
Is the pinnacle in the whole world.
S NAVEEN
#poetry#SN#review