I've been looking into asyncio topics a while now, but have never really found what I am looking for.
Basically I am developing a trading bot in python that should listen to trade opportunities which are held in for example MySQL.
So it needs to query MySQL every x seconds, and if there are any jobs to be started then start a job for it until finished
With the following code I simulate a new opportunity every time the while loop is done:
import asyncio, time
async def trade_task(counter):
print('task here')
time.sleep(20)
print('sleep for testing purposes to keep the instance running')
print('more tasks here')
counter = 0
while True:
loop = asyncio.get_event_loop()
task = loop.create_task(trade_task(counter))
print('hier')
try:
loop.run_until_complete(task)
except asyncio.CancelledError:
pass
counter += 1
time.sleep(10)
it kinda works, but it now waits for the trade_task function to finish, until proceeding and finishing the first run of the while loop.
I need something that created a task for trade_task in the background, and immediately proceed to check for another opportunity.
- periodic check to see if there is an opportunity
- if entry found, start task in background and keep looking for opportunity
- if entry found, start task in background and keep looking for opportunity
I've done this through threading before, but can asyncio do this better?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…