The scenario is that I have sync code executing in a couroutine that I don't have control over. At a given time, I'd like to be able to "force cancel" that coroutine. I'm running the sync code in a ThreadPoolExecutor
and trying to cancel the task. For example:
def execute():
# Some sync code
for i in range(5):
print(f'Hello {i}')
time.sleep(1)
print('Done executing sync task')
async def main(executor):
loop = asyncio.get_running_loop()
t = loop.run_in_executor(executor, execute)
# Simulate a cancel request coming in
await asyncio.sleep(1)
print('Cancelling')
t.cancel()
print('Cancelled')
await t
executor = concurrent.futures.ThreadPoolExecutor(max_workers=2)
asyncio.run(main(executor), debug=True)
The output is as follows:
Hello 0
Hello 1
Cancelling
... asyncio.exceptions.CancelledError stack trace ...
Cancelled
Hello 2
Hello 3
Hello 4
Ideally, I'd like to somehow terminate the running task. Is this possible? I'm also not married to using asyncio if something else if more appropriate here. Thanks for the suggestions.