Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import asyncio
- import functools
- import time
- PROCESS_TIMEOUT = 1.1
- loop = asyncio.get_event_loop()
- def warn_slow_process(*args):
- print('warn slow process')
- async def some_long_fun():
- print('entered some long fun, doing work')
- time.sleep(2.1)
- print('doing work done')
- async def process_request():
- # Analog of `asyncio.wait_for` but without cancelling task
- waiter = loop.create_future()
- timeout_handle = loop.call_later(PROCESS_TIMEOUT, asyncio.tasks._release_waiter, waiter)
- cb = functools.partial(asyncio.tasks._release_waiter, waiter)
- fut = asyncio.ensure_future(some_long_fun(), loop=loop)
- fut.add_done_callback(cb)
- try:
- try:
- await waiter
- except asyncio.futures.CancelledError:
- fut.remove_done_callback(cb)
- fut.cancel()
- raise
- if fut.done():
- print('Fut done, returning res')
- return fut.result()
- else:
- print('Fut slow, attaching cb')
- fut.remove_done_callback(cb)
- fut.add_done_callback(warn_slow_process)
- finally:
- timeout_handle.cancel()
- try:
- print('entering event loop')
- loop.run_until_complete(process_request())
- finally:
- print('closing event loop')
- loop.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement