Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add msg to task.cancel() method to allow distinguish the source of cancellation #320

Open
achimnol opened this issue Jul 5, 2022 · 1 comment

Comments

@achimnol
Copy link
Member

achimnol commented Jul 5, 2022

How about adding msg argument to task.cancel()?

TL;DR:

def _on_timeout(self, task: "asyncio.Task[None]") -> None:
    task.cancel(msg="timeout")  # <--- add the reason of cancellation
    self._state = _State.TIMEOUT
    # drop the reference early
    self._timeout_handler = None

This would be useful to distinguish the reason of cancellation in library's user programs.

@ljluestc
Copy link

ljluestc commented Sep 5, 2023

import asyncio

class CustomTask(asyncio.Task):
def cancel(self, msg=None):
self._msg = msg
super().cancel()

def _on_timeout(self, task: "asyncio.Task[None]") -> None:
task.cancel(msg="timeout") # Adding a custom reason for cancellation
self._state = _State.TIMEOUT
# Drop the reference early
self._timeout_handler = None

Replace asyncio.Task with CustomTask wherever you want to use it

async def main():
loop = asyncio.get_event_loop()
task = loop.create_task(async_func())
await asyncio.sleep(1)
task.cancel("custom_reason")

loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants