Download keep_alive.py from jam134/test2: direct link, hf CLI and curl.
- Browser
- Download file 1.16 kB
-
https://huggingface.co/spaces/jam134/test2/resolve/main/keep_alive.py
- Command line
-
hf download hf://spaces/jam134/test2/keep_alive.py
-
curl -L -o keep_alive.py https://huggingface.co/spaces/jam134/test2/resolve/main/keep_alive.py
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秒再重試 | |