You need to enable JavaScript to run this app. 如何让while循环内的if语句仅执行一次?解决定点通知重复弹出问题
优惠活动
大模型
产品
解决方案
定价
更多

如何让while循环内的if语句仅执行一次?解决定点通知重复弹出问题

问题原因
  • 时间获取位置错误:now = datetime.now() 写在了while True循环外部,只会在程序启动时获取一次当前时间,后续循环全程复用这个固定时间值,只要启动时间刚好命中你设置的触发时间点,就会无限触发通知。
  • 无循环间隔:死循环没有加休眠逻辑,会以CPU最高频率反复执行判断,哪怕修复了时间获取逻辑,同一分钟内也会反复触发通知。
  • 无已触发标记:同一分钟内只要判断命中就会弹通知,没有记录对应时间点是否已经推送过,会重复触发。
修复方案

修复后的完整代码如下:

from win10toast import ToastNotifier
from datetime import datetime
import time

toaster = ToastNotifier()
# 记录当天已经触发过的时间点,避免重复推送
triggered_times = set()

while True:
    # 每次循环重新获取当前时间
    now = datetime.now()
    current_time = now.strftime('%I:%M %p')
    # 每日0点清空触发记录,保证第二天可以正常触发
    if current_time == "00:00 AM":
        triggered_times.clear()
    # 仅当前时间符合要求且未触发过时才推送通知
    target_times = {"1:23 PM", "4:43 PM", "7:32 PM", "8:44 PM", "6:02 AM"}
    if current_time in target_times and current_time not in triggered_times:
        toaster.show_toast("Bot:", f"It's {current_time}")
        triggered_times.add(current_time)
    # 每次循环休眠1秒,降低CPU占用
    time.sleep(1)

内容的提问来源于stack exchange,提问作者Blue Duck

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 19:15:04