test2 / keep_alive.py
jam134's picture
Update keep_alive.py
38f3fd2 verified
Raw History Blame Contribute Delete
1.16 kB
import time
import threading
import websocket
import os
def on_open(ws):
print("Connection opened")
def run(*args):
while True:
time.sleep(30 * 60) # 每30秒發送一次心跳
ws.send("ping") # 發送心跳消息
threading.Thread(target=run).start()
def on_close(ws):
print("Connection closed")
def on_message(ws, message):
print(f"Message received: {message}")
def keep_alive_websocket(url):
while True:
try:
ws = websocket.WebSocketApp(
url,
on_open=on_open,
on_close=on_close,
on_message=on_message,
)
ws.run_forever()
# 保持連接5分鐘
print(f"Staying connected for 5 minutes: {url}")
time.sleep(5 * 60)
print(f"Disconnecting from: {url}")
ws.close() # 手動關閉連接
time.sleep(30 * 60) # 等待5分鐘再重新連接
except Exception as e:
print(f"Error: {e}. Reconnecting in 5 seconds...")
time.sleep(5) # 出錯後等待5秒再重試