Issue
I currently have this piece of code running just fine using AsyncIO.
async def main():
while(1):
loop.create_task(startAsyncJob())
await asyncio.sleep(1)
async def startAsyncJob():
#myCodeHere
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
I tried to add a multithreading layer so I can run concurrently multiple pieces of what inside my "main". So I extracted its code, put it in its own function AsyncJobThread
that I launch through my new main function using threads:
def main():
try:
_thread.start_new_thread( AsyncJobThread, (1))
_thread.start_new_thread( AsyncJobThread, (15))
except:
print ("Error: unable to start thread")
async def AsyncJobThread(frequence):
while(1):
loop.create_task(startAsyncJob())
await asyncio.sleep(frequence)
async def startAsyncJob():
#myCodeHere
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
However the current implementation gives me the following error:
sys:1: RuntimeWarning: coroutine 'AsyncJobThread' was never awaited
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Solution
As requested, here's your code modified to use asyncio.gather
.
async def main():
await asyncio.gather(
AsyncJobThread(1),
AsyncJobThread(15),
)
async def AsyncJobThread(frequence):
loop = asyncio.get_event_loop()
while True:
loop.create_task(startAsyncJob())
await asyncio.sleep(frequence)
async def startAsyncJob():
#myCodeHere
asyncio.run(main())
You could also get a reference to the loop and pass it into AsyncJobThread
if you prefer.
Answered By - dirn
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.