Here is my code, I want my_reader
to wait maximum 5 seconds for a future then do something with the my_future.result()
. Please note that my_reader
is not a coroutine , it is a callback .
import asyncio, socket
sock = ...
async def my_coroutine():
...
def my_reader():
my_future = asyncio.Future()
...
# I want to wait (with a timeout) for my_future
loop = asyncio.get_event_loop()
loop.add_reader(sock, my_reader)
loop.run_forever()
loop.close()
I don't want to use either:
AbstractEventLoop.create_datagram_endpoint()
AbstractEventLoop.create_connection()
The socket I have is returned from another module and I have to read packets with a given size. The transfer must happen under 5 seconds.
How to wait for a future inside a callback?
Sorry, waiting in callbacks is impossible. Callback should be executed instantly by definition -- otherwise event loop hangs on callback execution period.
Your logic should be built on coroutines but low-level on_read callback may inform these coroutines by setting a value of future.
See aiopg.connection for inspiration. The callback is named Connection._ready
.
You should run the coroutine separately and send data to it from the callback via Queue.
Look on this answer:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.