spacepaste

  1.  
  2. #!/usr/bin/python3.7
  3. import asyncio
  4. def get_future(n):
  5. fut = asyncio.Future()
  6. # Set fut done after n seconds
  7. asyncio.ensure_future(asyncio.sleep(n)).add_done_callback(fut.set_result)
  8. return fut
  9. async def task():
  10. while True:
  11. fut = get_future(2)
  12. waiter = asyncio.ensure_future(asyncio.wait_for(fut, 3))
  13. try:
  14. await asyncio.shield(waiter)
  15. except asyncio.CancelledError:
  16. print('Cancelled; continue waiting')
  17. await waiter
  18. break
  19. async def killer(fut):
  20. await asyncio.sleep(1)
  21. fut.cancel()
  22. async def main():
  23. t0 = asyncio.ensure_future(task())
  24. t1 = asyncio.ensure_future(killer(t0))
  25. await t0
  26. asyncio.run(main())
  27.