Reputation: 5783
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?
Upvotes: 1
Views: 2222
Reputation: 335
You should run the coroutine separately and send data to it from the callback via Queue.
Look on this answer:
https://stackoverflow.com/a/29475218/1112457
Upvotes: 0
Reputation: 17366
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
.
Upvotes: 2