如何让类中的方法每次执行后等待60秒再重复执行?
非阻塞式定期执行类中ROC方法的方案
由于你无法使用多线程/进程,且time.sleep(60)会阻塞主程序,以下两种基于标准库的非阻塞方案可以满足需求:
方案一:基于datetime的轮询式调度
在类中维护上次执行的时间戳,在主程序的循环里定期检查时间差,达到60秒时触发ROC方法,同时保证主程序其他任务正常运行。
示例代码
import datetime import time class YourTradingClass: def __init__(self): self.last_roc_run = None # 记录ROC上次执行时间 # 其他初始化逻辑(比如初始化df、tick的存储) def ROC(self, df, tick): global start_time global timespan start_time = tick['exchange_timestamp'] prev_volume = tick['volume_traded'] # 更新上次执行时间 self.last_roc_run = datetime.datetime.now() # 主程序运行逻辑 if __name__ == "__main__": trading_instance = YourTradingClass() # 假设这里是你的数据初始化 target_df = ... latest_tick = ... while True: # 主程序的其他业务逻辑(比如更新tick数据、处理其他指标) # ... # 检查是否满足ROC执行条件 current_time = datetime.datetime.now() if (trading_instance.last_roc_run is None or (current_time - trading_instance.last_roc_run).total_seconds() >= 60): trading_instance.ROC(target_df, latest_tick) # 短暂休眠减少CPU占用,不影响主程序响应 time.sleep(0.1)
方案二:使用sched模块实现定时调度
利用Python标准库sched的调度器,将ROC方法安排为每隔60秒执行一次,通过非阻塞方式运行调度器,不影响主程序其他任务。
示例代码
import sched import time class YourTradingClass: def __init__(self, scheduler): self.scheduler = scheduler self.target_df = ... # 初始化你的df数据 self.latest_tick = ... # 初始化你的tick数据 # 首次安排ROC执行 self._schedule_next_roc() def ROC(self): global start_time global timespan start_time = self.latest_tick['exchange_timestamp'] prev_volume = self.latest_tick['volume_traded'] # 安排下一次60秒后执行 self._schedule_next_roc() def _schedule_next_roc(self): # 计算60秒后的执行时间戳 next_run_time = time.time() + 60 # 把ROC方法加入调度队列 self.scheduler.enterabs(next_run_time, 1, self.ROC) # 主程序运行逻辑 if __name__ == "__main__": # 初始化调度器,使用系统时间作为基准 scheduler = sched.scheduler(time.time, time.sleep) trading_instance = YourTradingClass(scheduler) while True: # 主程序的其他业务逻辑(比如实时更新tick数据) # ... # 非阻塞运行调度器:检查是否有到期任务,执行后立即返回 scheduler.run(blocking=False) # 短暂休眠降低CPU消耗 time.sleep(0.1)
注意事项
- 如果tick数据是实时更新的,要确保每次执行ROC时使用的是最新的tick数据,避免使用初始化时的旧数据。
- 主程序的循环必须持续运行,否则定时逻辑会中断;如果是GUI或异步服务,可以将调度检查逻辑嵌入到现有事件循环中。
- 建议替换ROC方法中的全局变量为类实例属性,减少全局变量带来的耦合问题。
内容的提问来源于stack exchange,提问作者charles sean
相关产品推荐
相关产品推荐

