Python实现闹钟时时间匹配while循环不生效问题排查
问题原因
- 你仅在程序初始化阶段获取了一次当前时间,
currentDate变量不会自动更新,永远等于程序启动时的时间,因此后续循环中永远无法匹配到闹钟时间。 - 无限循环没有添加休眠逻辑,会持续占满单个CPU核心,造成不必要的性能浪费。
修复代码
修改逻辑:将当前时间的获取逻辑移入循环内部,每次判断前拉取最新系统时间,同时添加1秒休眠降低CPU占用,优化了冗余的全局导入,也将交互提示翻译成了中文:
from datetime import datetime from time import sleep timeNow = datetime.now() currentDate = timeNow.strftime('%d/%m/%y %H:%M') print(f'当前日期时间为:{currentDate}') userInputDate = 'None' alarmDate = '' while userInputDate not in ('Y','N'): userInputDate = input('是否要设置今日的闹钟?(y/n): ').upper() if userInputDate == 'Y': userInput = input('请输入闹钟时间,格式为 %H:%M : ') alarmDate = timeNow.strftime('%d/%m/%y')+ ' ' + userInput print(f'闹钟已设置为:{alarmDate}') else: userInput = input('请输入闹钟时间,格式为 %d/%m/%y %H:%M : ') alarmDate = userInput print(f'闹钟已设置为:{alarmDate}') while True: # 每次循环重新获取最新时间 current_time = datetime.now() currentDate = current_time.strftime('%d/%m/%y %H:%M') if currentDate == alarmDate: print('闹钟响了!') break # 休眠1秒降低CPU占用 sleep(1)
注意事项
用户输入的时间格式必须和要求的格式完全一致,包括斜杠、冒号、数字位数,否则字符串匹配会失败,闹钟无法正常触发。
内容的提问来源于stack exchange,提问作者Myk1709
相关产品推荐
相关产品推荐

