task.cancel

  • 取消任务

    1. task.cancel()
  • 示例:

  1. from usr import uasyncio as asyncio
  2. async def bar(n):
  3. print('Start cancellable bar()')
  4. while True:
  5. await asyncio.sleep(1)
  6. n += 1
  7. return n
  8. async def do_cancel(task):
  9. await asyncio.sleep(5)
  10. print('About to cancel bar')
  11. # 取消任务
  12. task.cancel()
  13. def main():
  14. task = asyncio.wait_for(bar(10), 7)
  15. asyncio.create_task(do_cancel(task))
  16. asyncio.sleep(1)
  17. asyncio.run(main())