import asyncio async def job(): print("job(): START...") try: await asyncio.sleep(5.0) except asyncio.CancelledError as e: print("job(): CANCELLED!", e) raise print("job(): DONE.") async def cancel_task_after(task, time): try: await asyncio.sleep(time) except asyncio.CancelledError: print("cancel_task_after(): CANCELLED!") task.cancel("Hello!") async def main(): task = asyncio.create_task(job()) # RUN/CANCEL task. try: await asyncio.gather(task, cancel_task_after(task, 1.0)) except asyncio.CancelledError as e: print("In running task, we encountered a cancellation! Excpetion message is: ", e) # GET result. try: result = task.result() except asyncio.CancelledError as e: print("Task has been cancelled, exception message is: ", e) else: print("Task result is: ", result) if __name__=="__main__": asyncio.run(main())