You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 10:54:06