简体   繁体   English

如何永远运行 2 个异步函数?

[英]How to run 2 async functions forever?

I'm trying to run 2 async functions forever.我正在尝试永远运行 2 个async函数。 Can someone help me?有人能帮我吗? My code and error message is provided below.下面提供了我的代码和错误消息。

Code:代码:

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())

Error:错误:

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

Well, there are few errors with your snippet code:好吧,您的代码段几乎没有错误:

  1. You can't name your first function as time because it'll generate a conflict with time built-in function您不能将您的第一个 function 命名为time ,因为它会与内置的time function 产生冲突
  2. Why are you passing loop as parameter if you're not gonna use it?如果您不打算使用它,为什么要将loop作为参数传递? It's useless.没用的。
  3. You can't await a function if it's not awaitable ie int is a synchronous built-in method.如果 function 不可等待,则您不能await它,即int是一个同步的内置方法。

Making the proper corrections it'll be something like this:进行适当的更正,它将是这样的:

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))

The line await asyncio.sleep(0.001) in stream() function is compulsory otherwise it won't never let the another_name() function runs. stream() function 中的await asyncio.sleep(0.001)行是强制性的,否则它永远不会让another_name() function 运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM