Как отменить длительную работу asyncio.Task? ⇐ Python

Программы на Python
Anonymous
Как отменить длительную работу asyncio.Task?

Сообщение Anonymous »

У меня есть следующий пример кода:

Код: Выделить всё

import asyncio
import concurrent.futures
import functools
import time

async def run_till_first_success(tasks, timeout=None):
results = []
exceptions = []
while tasks:
try:
async with asyncio.timeout(timeout):
done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED, timeout=timeout)
except TimeoutError:
print('timeout is catched')
for task in tasks:
task.cancel()  # this is not working!
return

# >>> this code doesn't actually matter
for task in done:
if task.exception():
exceptions.append(task.exception())
else:
results.append(task.result())
tasks = pending
if results or len(pending) == 0:
for task in pending:
task.cancel()
break
if not results:
raise exceptions[0]
return results[0]
# 

Подробнее здесь: [url]https://stackoverflow.com/questions/79046766/how-to-cancel-long-running-asyncio-task[/url]

Вернуться в «Python»