Call Coroutine Within Thread
Is it possible to make a thread run method async so it can execute coroutines inside it? I realise I am mixing paradigms - I am trying to integrate a 3rd party library that uses co
Solution 1:
You need to create a asyncio event loop, and wait until the coroutine complete.
import asyncio
from threading import Thread
class MyThread(Thread):
def run(self):
loop = asyncio.new_event_loop() # loop = asyncio.get_event_loop()
loop.run_until_complete(self._run())
loop.close()
# asyncio.run(self._run()) In Python 3.7+
async def _run(self):
while True:
print("MyThread::run() sync")
await asyncio.sleep(1)
# OR
# volume = await market_place.get_24h_volume()
t = MyThread()
t.start()
try:
t.join()
except KeyboardInterrupt:
pass
Post a Comment for "Call Coroutine Within Thread"