【问题标题】:python asyncio active looppython asyncio 主动循环
【发布时间】:2021-01-08 15:15:30
【问题描述】:

我一直在研究 asyncio 主题一段时间,但从未真正找到我想要的。

基本上,我正在用 python 开发一个交易机器人,它应该听听保存在例如 MySQL 中的交易机会。

所以它需要每隔 x 秒查询一次 MySQL,如果有任何作业要启动,则为它启动一个作业直到完成

使用以下代码,我在每次 while 循环完成时模拟一个新机会:

    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)

它有点工作,但它现在等待 trade_task 函数完成,直到继续并完成 while 循环的第一次运行。

我需要在后台为 trade_task 创建任务的东西,然后立即继续检查另一个机会。

  • 定期检查是否有机会
  • 如果找到条目,则在后台启动任务并继续寻找机会
  • 如果找到条目,则在后台启动任务并继续寻找机会

我以前通过线程完成了这个,但是 asyncio 可以做得更好吗?

【问题讨论】:

    标签: python-3.x python-asyncio cryptocurrency


    【解决方案1】:

    通常,应该只有一个主事件循环,所有任务都应该在那里运行,

    试试这样的,

    import asyncio
    from itertools import count
    
    
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    
    
    async def trade_task(counter):
        print('task here')
        # time.sleep is a blocking call and halts the execution of other tasks in the loop as well.
        await asyncio.sleep(20)
        print('sleep for testing purposes to keep the instance running')
        print('more tasks here')
    
        
    async def task_spawner():
        # if you want an infinite loop
        for counter in count():
            # this new task would run in bg
            loop.create_task(trade_task(counter))
            # While this one sleeps
            await asyncio.sleep(20)
    
        # if you have a fixed counter range (e.g. 10)
        # all run parallelly here
        await asyncio.gather(*(trade_task(counter) for for counter in range(10)))
            
    
    loop.run_until_complete(task_spawner())
    

    【讨论】:

      猜你喜欢
      • 2018-11-20
      • 2018-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多