Reputation: 253
I'm making a simple Python function where i have a function running on the main thread, called Updater
, which now only prints something but it will do other tasks, and it's called by schedule
, and another function that i want to run in parallel, so for that i'm using threading.
Here is my attempt:
import websocket, json, time, schedule, logging, cfscrape, threading, requests
def Run():
def process_message(ws,msg):
print(msg)
def Connect():
websocket.enableTrace(False)
ws = websocket.WebSocketApp("wss://stream.binance.com/stream?streams=btcusdt@depth", on_message = process_message)
ws.run_forever()
def Updater():
print('Updating..')
threading.Thread(target=Run).start()
schedule.every(1).seconds.do(Updater)
while True:
schedule.run_pending()
time.sleep(1)
What i'm trying to do is to have this script executing the websocket connection and the scheduled function at the same time in parallel using threads. The problem with my code is that Run
is not getting started. Only Updater
will start executing.
Can anyone help me out on this? Am i using threads the wrong way? Thanks in advance.
Upvotes: 1
Views: 1233
Reputation: 36
You're setting the Run()
function as the target for the thread. However when you run the function all it does is defining the functions process_message
and Connect
, and neither calling them nor returning them. So actually your thread ends right after you started it, doing nothing, which is why it won't print anything.
The simplest thing you can do to make it do something is:
import websocket, json, time, schedule, logging, cfscrape, threading, requests
def Run():
def process_message(ws,msg):
print(msg)
def Connect():
websocket.enableTrace(False)
ws = websocket.WebSocketApp("wss://stream.binance.com/stream?streams=btcusdt@depth", on_message = process_message)
ws.run_forever()
# no need to call process_message since it will be called automatically by
# the WebSocketApp created by Connect
Connect() # Actually call the Connect function, so that it is used in your thread
def Updater():
print('Updating..')
threading.Thread(target=Run).start()
schedule.every(1).seconds.do(Updater)
while True:
schedule.run_pending()
time.sleep(1)
I would also advise against naming functions with an uppercase letter as first character, as by convention (see pep-8 about naming convention) this should be reserved for classes.
Upvotes: 2
Reputation: 2118
Might be that it actually runs but doesn't print because of buffering, try doing:
print(msg, flush=True)
Also, you never call the connect function. call it under its declaration with the in Run indentation
Upvotes: 1