Python使用内置sched库定时执行函数触发TypeError问题求解
报错原因
sched模块内部计算任务等待间隔时,会执行目标时间 - 当前时间的减法操作。你初始化sched.scheduler时传入的时间函数是time.localtime,该函数返回time.struct_time类型的对象,Python原生不支持两个time.struct_time对象直接做减法,因此触发类型错误。
同时enterabs方法要求传入的目标时间类型,必须和调度器初始化时时间函数的返回值类型完全匹配,你传入time.strptime生成的struct_time对象刚好对应,但类型本身不支持减法运算才是问题根源。
修复方案
推荐使用通用的时间戳方案修改代码,修改后可正常运行:
import sched, time def action(): print('Hello world') # 初始化调度器改用返回浮点时间戳的time.time作为时间函数 s = sched.scheduler(time.time, time.sleep) # 将时间字符串先转成struct_time,再转成时间戳格式 target_timestamp = time.mktime(time.strptime('Fri Oct 22 17:20:00 2021')) s.enterabs(target_timestamp, 0, action) s.run()
内容的提问来源于stack exchange,提问作者Jimmy
相关产品推荐
相关产品推荐

