如何永远运行2个异步功能?

问题描述

我正在尝试永远运行2个async函数。有人能帮我吗?下面提供了我的代码和错误消息。

代码:

import websockets
import asyncio
import json
import time

async def time(loop):
    while True:
        millis = await int(round(time.time() * 1000))
        print(millis)
        await asyncio.sleep(0.001)

async def stream(loop):
    async with websockets.connect('wss://www.bitmex.com/realtime?subscribe=trade:XBTUSD') 
                    as websocket:
        while True:
            try:
                data = await websocket.recv()
                data = json.loads(data)
                print(data['data'][-1]['price'])
            except KeyError:
                pass
            except TypeError:
                pass

loop = asyncio.get_event_loop()

async def main():
    await asyncio.gather(loop.run_until_complete(stream(loop)),loop.run_until_complete(time(loop)))

if __name__ == "__main__":
    asyncio.run(main())

错误:

Exception has occurred: RuntimeError
Cannot run the event loop while another loop is running

解决方法

好,您的代码段错误很少:

  1. 您不能将第一个函数命名为time,因为它会与time内置函数产生冲突
  2. 为什么不使用loop作为参数呢?这没用。
  3. 如果无法等待某个功能,则无法await,即int是一个内置的同步方法。

进行正确的更正将是这样的:

import websockets
import asyncio
import json
import time

async def another_name():
    while True:
        millis = int(round(time.time() * 1000))
        print(millis)
        await asyncio.sleep(0.001)

async def stream():
    async with websockets.connect('wss://www.bitmex.com/realtime?subscribe=trade:XBTUSD') 
                    as websocket:
        while True:
            try:
                data = await websocket.recv()
                data = json.loads(data)
                print(data['data'][-1]['price'])
            except KeyError:
                pass
            except TypeError:
                pass
            await asyncio.sleep(0.001) #Added

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    coros = []
    coros.append(another_name())
    coros.append(stream())
    loop.run_until_complete(asyncio.gather(*coros))

await asyncio.sleep(0.001)函数中的行stream()是强制性的,否则它将永远不会让another_name()函数运行。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...