Search code examples
pythonmultithreadingwebsocketpython-asynciopython-multithreading

Running Python WebSocket While Concurrently Checking Other Unrelated Information with a Function Call Every Minute


I have a WebSocket I run generally as follows:

import websocket

def on_message(ws, message):
    ...

ws = websocket.WebSocketApp(socket, on_open=on_open, on_message=on_message,
                        on_close=on_close)
ws.run_forever(ping_interval=5, ping_timeout=-1)

I want this to run but also perform another check from a function on every minute that elapses. Is there any way I can do this. I have heard of maybe threading or asyncio but have never used either. Any advice would be greatly appreciated.


Solution

  • The simplest approach would be using threading

    import websocket
    import threading
    
    def runs_every_minute():
        while True:
            # do something
            time.sleep(60)
    
    
    def on_message(ws, message):
        ...
    
    
    t = threading.Thread(target=runs_every_minute)
    t.start()  # starts the thread
    
    ws = websocket.WebSocketApp(socket, on_open=on_open, on_message=on_message,
                            on_close=on_close)
    ws.run_forever(ping_interval=5, ping_timeout=-1)