运行 在 python 的特定时间运行 - TypeError

Run function at a specific time in python - TypeError

我想使用内置的 python 库 sched

在特定时间点将函数安排到 运行

我一直在查看 Run function at a specific time in python 的答案中的代码。

问题是,当我 运行 答案中的代码时,我得到 TypeError。为什么?

谢谢!

import sched, time

def action():
    print('Hello world')

s = sched.scheduler(time.localtime, time.sleep)
s.enterabs(time.strptime('Fri Oct 22 17:20:00 2021'), 0, action)
s.run()

# ERROR
TypeError: unsupported operand type(s) for -: 'time.struct_time' and 'time.struct_time' 

您收到类型错误,因为 time.struct_time 对象没有内置的减法方法。 time.localtime() 和 time.strptime() 都函数 return 一个 time.struct_time 对象。换句话说,sched.scheduler 无法确定当前时间与您指定的时间之间的时间差(延迟多长时间)。有关 time.struct_time 对象的更多信息,请参见 here

如果您将代码修改为类似于以下内容,它将起作用。

import sched, time

def action():
    print('Hello world')

s = sched.scheduler(time.time, time.sleep)
s.enterabs(time.mktime(time.strptime('Sun Oct 24 21:05:00 2021')), 0, action)
s.run()

time.mktime() 函数允许将 time.struct_time 对象转换为浮点值。从 documentation 来看,这似乎是专门添加的,因此它可以与 time.time() 一起使用,return 也是一个浮点值。通过指示调度程序结合使用 time.time 函数和 time.mktime 函数,它允许减去消除 TypeError 的浮点值。然后将该差异传递给延迟函数(脚本中的time.sleep)以延迟任务。