I have an asyncio.Task
that I need to cancel after some amount of time. Before cancelling, the task needs to do some cleanup. According to the docs, I should just be able to call task.cancel or asyncio.wait_for(coroutine, delay)
and intercept an asyncio.TimeoutError
in the coroutine, but the following example is not working. I've tried intercepting other errors, and calling task.cancel
instead, but neither have worked. Am I misunderstanding how cancelling a task works?
@asyncio.coroutine
def toTimeout():
try:
i = 0
while True:
print("iteration ", i, "......"); i += 1
yield from asyncio.sleep(1)
except asyncio.TimeoutError:
print("timed out")
def main():
#... do some stuff
yield from asyncio.wait_for(toTimeout(), 10)
#... do some more stuff
asyncio.get_event_loop().run_until_complete(main())
asyncio.get_event_loop().run_forever()
The documentation for
asyncio.wait_for
specifies that it will cancel the underlying task, and then raiseTimeoutError
from thewait_for
call itself:And you are correct that task cancellation can indeed be intercepted:
Note that the docs specify that
CancelledError
is thrown into the coroutine, notTimeoutError
.If you make that adjustment, things work the way you expect:
Output:
As you can see, now
'timed out'
gets printed before theTimeoutError
is raised bywait_for
.