Python中的计划函数未启动
我编写了以下脚本,它连接到websocket并从中接收一些数据。当这个脚本运行时,我尝试每2秒运行一个函数。在本例中,该函数只打印一条消息,但当然这是为了调试,它将在将来执行其他任务 我的问题是,Python中的计划函数未启动,python,python-3.x,Python,Python 3.x,我编写了以下脚本,它连接到websocket并从中接收一些数据。当这个脚本运行时,我尝试每2秒运行一个函数。在本例中,该函数只打印一条消息,但当然这是为了调试,它将在将来执行其他任务 我的问题是,Printer()没有开始运行,我没有看到每2秒出现一次消息。我知道问题在于Connect()有自己的线程,所以在Connect()停止工作之前,不会安排Printer()。我希望Printer()在从websocket接收数据时运行。有什么办法吗?让它异步?使用更多线程 import websocke
Printer()
没有开始运行,我没有看到每2秒出现一次消息。我知道问题在于Connect()
有自己的线程,所以在Connect()
停止工作之前,不会安排Printer()
。我希望Printer()
在从websocket接收数据时运行。有什么办法吗?让它异步?使用更多线程
import websocket, json, time, schedule, logging, cfscrape
from websocket import create_connection
try:
import thread
except ImportError:
import _thread as thread
MyList = []
MexCoinsToMonitor = ['XBTUSD']
LastOrder = format(float(time.time()), '.0f')
BU = cfscrape.create_scraper()
def process_message(ws,msg):
try:
message = json.loads(msg)
print(message)
except Exception as e:
print(e)
def Printer():
print('hello')
def on_error(ws, error):
print('Error')
def on_close(ws):
Checker()
def on_open(ws):
def run(*args):
for value in MexCoinsToMonitor:
tradeStr=""" {"op": "subscribe", "args": ["orderBookL2_25:%s"]} """%(value)
ws.send(tradeStr)
time.sleep(1)
thread.start_new_thread(run, ())
def Checker():
global LastOrder
TimeDiff = float(time.time()) - float(LastOrder)
print (LastOrder, TimeDiff)
if TimeDiff > 20:
ws = websocket.WebSocketApp("wss://www.bitmex.com/realtime", on_message = process_message, on_error = on_error, on_close = on_close)
ws.on_open = on_open
ws.run_forever()
def Connect():
websocket.enableTrace(False)
ws = websocket.WebSocketApp("wss://www.bitmex.com/realtime", on_message = process_message, on_error = on_error, on_close = on_close)
ws.on_open = on_open
ws.run_forever()
Connect()
schedule.every(2).seconds.do(Printer)
while True:
schedule.run_pending()
time.sleep(2)
为了调度,我使用了
调度
模块。您确实可以使其异步。连接工作时将运行打印机。您可以为此使用线程模块
import threading
threading.Thread(target=Printer).start()
那会启动打印机。这样,您就可以连接打印机,而不必完成打印
如果要继续调用该函数,只需使用while循环
import threading
import time
while True:
threading.Thread(target=Printer).start()
time.sleep(2)
我发现很难理解你想要实现的目标。我希望这有帮助!嘿,谢谢你的回答!到底是什么让人难以理解?是因为我努力实现的目标很难实现,还是因为我的问题不够清楚?如果是后者,我可以编辑我的问题:)很难知道什么东西应该做,什么时候应该做。另外,我不是很喜欢WebSocket,所以可能也是我。好吧!非常感谢。所以我尝试线程,函数在我启动脚本时运行,唯一的问题是它没有被调度,不会每2秒运行一次。我在试着理解为什么!问题是它需要并行运行才能连接,所以当连接工作并发送数据时,每隔2秒我还需要看到“hello”被打印出来