Refactor Uptime Kuma heartbeat implementation to use UptimeKumaMonitor class, enhancing maintainability and logging capabilities
This commit is contained in:
@@ -2,15 +2,19 @@ import time
|
||||
import os
|
||||
import sys
|
||||
import pyodbc
|
||||
import requests
|
||||
from config import SQL_SERVER_CONN, ACCESS_DRIVER, SYNC_MAPPING, POLL_INTERVAL, LOG_TABLE_CONFIG, UPTIME_KUMA_CONFIG
|
||||
import db_utils
|
||||
from log_utils import (LoggerManager, log_success, log_error, log_warning, log_info, log_processing,
|
||||
log_skip, log_critical, log_start, log_stop, log_file, log_database, log_sync)
|
||||
from uptime_kuma_utils import UptimeKumaMonitor
|
||||
|
||||
# 初始化日志管理器
|
||||
LoggerManager("run_incremental_sync", log_prefix="incremental")
|
||||
|
||||
# 初始化 Uptime Kuma 监控器
|
||||
uptime_monitor = UptimeKumaMonitor(UPTIME_KUMA_CONFIG)
|
||||
uptime_monitor.set_logger(log_warning)
|
||||
|
||||
# ================= 主逻辑 =================
|
||||
|
||||
def process_sync_task():
|
||||
@@ -185,29 +189,7 @@ def process_sync_task():
|
||||
except: pass
|
||||
|
||||
# ================= Uptime Kuma 心跳 =================
|
||||
|
||||
_last_heartbeat_time = 0
|
||||
|
||||
def send_heartbeat():
|
||||
"""发送心跳信号到 Uptime Kuma"""
|
||||
global _last_heartbeat_time
|
||||
|
||||
if not UPTIME_KUMA_CONFIG.get('enabled', False):
|
||||
return
|
||||
|
||||
try:
|
||||
url = UPTIME_KUMA_CONFIG['push_url']
|
||||
params = {
|
||||
'status': 'up',
|
||||
'msg': 'OK',
|
||||
'ping': ''
|
||||
}
|
||||
response = requests.get(url, params=params, timeout=5)
|
||||
response.raise_for_status()
|
||||
_last_heartbeat_time = time.time()
|
||||
except Exception as e:
|
||||
# 心跳失败不影响主逻辑,仅记录日志
|
||||
log_warning(f"心跳发送失败: {e}")
|
||||
# 使用 uptime_kuma_utils.UptimeKumaMonitor 替代原有实现
|
||||
|
||||
if __name__ == "__main__":
|
||||
log_start("增量同步服务已启动 (配置驱动模式)")
|
||||
@@ -218,7 +200,7 @@ if __name__ == "__main__":
|
||||
log_info("=" * 70)
|
||||
|
||||
# 启动时发送第一次心跳
|
||||
send_heartbeat()
|
||||
uptime_monitor.send_heartbeat()
|
||||
|
||||
try:
|
||||
while True:
|
||||
@@ -226,9 +208,7 @@ if __name__ == "__main__":
|
||||
has_work = process_sync_task()
|
||||
|
||||
# 检查是否需要发送心跳
|
||||
time_since_last_heartbeat = time.time() - _last_heartbeat_time
|
||||
if time_since_last_heartbeat >= UPTIME_KUMA_CONFIG['heartbeat_interval']:
|
||||
send_heartbeat()
|
||||
uptime_monitor.check_and_send_heartbeat()
|
||||
|
||||
# 如果有工作,说明可能还有积压,休息短一点(0.1s)
|
||||
# 如果没工作,休息标准间隔(5s)
|
||||
@@ -243,10 +223,4 @@ if __name__ == "__main__":
|
||||
time.sleep(5)
|
||||
finally:
|
||||
# 停止时发送心跳停止信号(可选)
|
||||
if UPTIME_KUMA_CONFIG.get('enabled', False):
|
||||
try:
|
||||
url = UPTIME_KUMA_CONFIG['push_url']
|
||||
params = {'status': 'down', 'msg': 'Service stopped'}
|
||||
requests.get(url, params=params, timeout=5)
|
||||
except:
|
||||
pass
|
||||
uptime_monitor.send_stop_signal()
|
||||
Reference in New Issue
Block a user