# create an event loop shared by all sub components.
self._event_loop = asyncio.get_event_loop()
if not self._event_loop.is_running():
self._thread = threading.Thread(
target=asyncio.get_event_loop().run_forever
)
self._thread.start()
# set event loop to debug mode for exception logging
self._event_loop.set_debug(True)
-
Python Event Loop
-
# submit function into event loop future = asyncio.run_coroutine_threadsafe( self.connection.close(), self.shared_event_loop ) # method 1. add callback to future future.add_done_callback(lambda fut: self._kill_event_loop()) # method 2. wait for future result result = fut.result() # blocking
-
# methods to add async function to loop task = asyncio.create_task(coro) # method 1 task = asyncio.ensure_future(coro) # method 2 task.add_done_callback(callback) # callback when future done. # wait for Future result with a timeout future = asyncio.run_coroutine_threadsafe(coro_func(), self.shared_event_loop) result = future.result(timeout)
-
# waiting for task to complete? # haven't tested but its much cleaner... async def _start(self): yield from event_loop.call_soon(...)
-
Wait for async function to complete (invoke from sync function)
yield asyncio.wait_for(self.close_session(), timeout=2)