Advertisement
surik00

loop.call_later doesnt work properly

Jul 11th, 2018
163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.31 KB | None | 0 0
  1. import asyncio
  2. import functools
  3. import time
  4.  
  5.  
  6. PROCESS_TIMEOUT = 1.1
  7. loop = asyncio.get_event_loop()
  8.  
  9.  
  10. def warn_slow_process(*args):
  11.     print('warn slow process')
  12.  
  13.  
  14. async def some_long_fun():
  15.     print('entered some long fun, doing work')
  16.     time.sleep(2.1)
  17.     print('doing work done')
  18.  
  19.  
  20. async def process_request():
  21.     # Analog of `asyncio.wait_for` but without cancelling task
  22.     waiter = loop.create_future()
  23.     timeout_handle = loop.call_later(PROCESS_TIMEOUT, asyncio.tasks._release_waiter, waiter)
  24.     cb = functools.partial(asyncio.tasks._release_waiter, waiter)
  25.  
  26.     fut = asyncio.ensure_future(some_long_fun(), loop=loop)
  27.     fut.add_done_callback(cb)
  28.  
  29.     try:
  30.         try:
  31.             await waiter
  32.         except asyncio.futures.CancelledError:
  33.             fut.remove_done_callback(cb)
  34.             fut.cancel()
  35.             raise
  36.  
  37.         if fut.done():
  38.             print('Fut done, returning res')
  39.             return fut.result()
  40.         else:
  41.             print('Fut slow, attaching cb')
  42.             fut.remove_done_callback(cb)
  43.             fut.add_done_callback(warn_slow_process)
  44.     finally:
  45.         timeout_handle.cancel()
  46.  
  47. try:
  48.     print('entering event loop')
  49.     loop.run_until_complete(process_request())
  50. finally:
  51.     print('closing event loop')
  52.     loop.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement