使用Python在指定时间运行程序(非系统调度器):代码无报错但未执行排查
问题分析与修复方案
核心问题点
- 时间判断逻辑失效:
start = datetime.datetime.now()仅在程序启动时获取一次时间,后续循环中不会更新。end - start的差值只会随时间推移越来越大,永远不可能等于0,导致触发条件永远无法满足。 - 时间比较精度问题:即便更新当前时间,直接判断
当前时间 - end == 0也几乎无法命中——datetime对象包含毫秒级精度,系统时间很难刚好和设定的end时间完全一致。 - CPU资源浪费:无间隔的
while(True)循环会持续占用CPU,影响系统性能。 - 代码结构不合理:
import subprocess放在循环内部,每次循环都会执行导入操作,完全没必要。
修复后的代码示例
import datetime import subprocess import time # 生成批处理文件 bat_path = r"D:\Cyber_security\Python\cal.bat" with open(bat_path, "w+") as mybat: # 使用r前缀避免转义问题 mybat.write(r"C:\Windows\system32\calc.exe") # 设定目标执行时间 target_time = datetime.datetime(2022, 7, 12, 17, 29, 10) while True: current_time = datetime.datetime.now() # 判断当前时间是否已达到或超过目标时间 if current_time >= target_time: subprocess.call([bat_path]) break # 执行完成后退出循环 # 每秒检查一次,降低CPU占用 time.sleep(1)
关键优化说明
- 实时获取当前时间:每次循环都调用
datetime.datetime.now()获取最新时间,确保判断逻辑有效。 - 调整判断条件:用
current_time >= target_time替代精确相等判断,避免因精度问题错过触发时机。 - 添加休眠机制:
time.sleep(1)让循环每秒执行一次,大幅降低CPU占用率。 - 优化代码结构:将所有导入语句放在开头,使用
with语句自动管理文件句柄,避免手动关闭文件可能出现的遗漏。
内容的提问来源于stack exchange,提问作者ijahan
相关产品推荐
相关产品推荐

