Python定时监测任务如何避免重复告警且保持程序持续运行
问题原因
你的代码未存储上一次检测的告警触发状态与相关匹配值,只要检测时条件持续满足,每5秒的定时调用就会重复打印告警信息。
解决方案
新增状态变量记录上一次的触发状态和告警唯一标识,仅当状态从「不满足」变为「满足」或告警关键值发生变化时才打印告警。修改后的完整代码如下:
import schedule import time # [...保留你原有上方的其他代码,包括avc_red、fivesec_datetime等变量定义...] # 新增状态存储变量:第一个告警的触发状态和唯一标识 last_red_alert_triggered = False last_red_alert_unique_key = "" # 新增状态存储变量:第二个告警的触发状态和唯一标识 last_another_red_alert_triggered = False last_another_red_alert_unique_key = "" def Alert_Red(): global last_red_alert_triggered, last_red_alert_unique_key global last_another_red_alert_triggered, last_another_red_alert_unique_key # 第一个告警逻辑 first_cond_satisfied = advColor == avc_red and delta <= fivesec_datetime # 构造当前告警的唯一标识,可根据实际业务调整组合字段,保证不同告警对应不同值即可 first_current_key = f"{advColor}_{delta}_{link}" if first_cond_satisfied: if not last_red_alert_triggered or first_current_key != last_red_alert_unique_key: print('New RED advisory please check the following link: ', link) # 更新状态 last_red_alert_triggered = True last_red_alert_unique_key = first_current_key else: # 条件不满足时重置状态,下次再满足会重新触发 last_red_alert_triggered = False last_red_alert_unique_key = "" # 第二个告警逻辑 second_cond_satisfied = advColor1 == avc_red and adv_datetime1 == adv_datetime second_current_key = f"{advColor1}_{adv_datetime1}_{adv_datetime}_{link}" if second_cond_satisfied: if not last_another_red_alert_triggered or second_current_key != last_another_red_alert_unique_key: print('Another new RED advisory please check the following link: ', link) # 更新状态 last_another_red_alert_triggered = True last_another_red_alert_unique_key = second_current_key else: # 条件不满足时重置状态 last_another_red_alert_triggered = False last_another_red_alert_unique_key = "" schedule.every(5).seconds.do(Alert_Red) while True: schedule.run_pending() time.sleep(1)
效果说明
- 同一条件持续满足时,仅首次触发时打印一次告警
- 条件从满足变为不满足后再次满足时,会重新触发一次告警
- 告警相关的关键值发生变化时,即使之前触发过同类型告警,也会重新打印新的告警
内容的提问来源于stack exchange,提问作者Lareth
相关产品推荐
相关产品推荐

