Python自定义Timer类在循环中无法暂停持续递增问题求助
问题分析与解决:可暂停计时器在循环中无法正确暂停的原因
你的计时器在循环中无法正确暂停,主要有两个关键问题:
1. pause() 方法未做运行状态校验
当前的pause()方法没有判断计时器是否处于运行状态,当计时器已经暂停后,再次调用pause()会执行错误逻辑:
- 使用未被清除的旧
start_time计算从第一次启动到当前的时长 - 将这个错误的时长追加到
time_data中,导致总时长不断累加异常值
2. 循环中重复触发pause()
暂停后,timer.elapsed()返回的累计时长已经≥3,循环的条件判断会持续成立,每次循环都调用pause(),进一步导致time_data被错误追加。
修复方案
第一步:修正Timer类的核心方法
添加状态校验并修复resume()的计算错误:
from time import time class Timer: def __init__(self): self.time_data = [] self.is_started = False self.start_time = None def start(self): if self.is_started: return self.start_time = time() self.is_started = True return self def pause(self) -> None: # 仅当计时器运行时才执行暂停逻辑 if not self.is_started: return elapsed = time() - self.start_time self.is_started = False self.time_data.append(elapsed) def resume(self): if self.is_started: print("Timer is already running") return # 移除错误的+1,正确计算恢复计时的起始时间 self.start_time = time() - sum(self.time_data) self.is_started = True def elapsed(self): if self.is_started: current_elapsed = time() - self.start_time total_elapsed = sum(self.time_data) + current_elapsed else: total_elapsed = sum(self.time_data) return total_elapsed # 补充测试代码中用到的restart方法 def restart(self): self.time_data = [] self.is_started = False self.start_time = None
第二步:修正循环逻辑,避免重复暂停
在判断条件中加入计时器运行状态校验:
from time import sleep from timing import Timer timer = Timer() def start(): timer.start() def pause(): timer.pause() start() while True: current_elapsed = timer.elapsed() print(current_elapsed) # 仅在计时器运行且时长达标时执行暂停 if current_elapsed >= 3 and timer.is_started: pause() print("paused!") sleep(0.25)
修复后效果
运行修改后的代码,输出会保持在3秒左右不再增长,符合预期:
2.2578864097595215 2.5090396404266357 2.7601206302642822 3.011416435241699 paused! 3.011416435241699 3.011416435241699 ...
内容的提问来源于stack exchange,提问作者Z1scko
相关产品推荐
相关产品推荐

