Issue
I'm trying to run 2 async
functions forever. 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
Solution
Well, there are few errors with your snippet code:
- You can't name your first function as
time
because it'll generate a conflict withtime
built-in function - Why are you passing
loop
as parameter if you're not gonna use it ? It's useless. - You can't
await
a function if it's not awaitable i.e.int
is a synchronous built-in method.
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.
Answered By - Brad Figueroa
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.