如何使用Python安排一个不受系统时间变化影响的周期性任务

Vin*_*ent 5 python python-2.7

我正在使用python的sched模块定期运行一个任务,我想我遇到过一个bug.

我发现它依赖于运行python脚本的系统的时间.例如,假设我想每5秒运行一次任务.如果我转发系统时间,则计划任务将按预期运行.但是,如果我将系统时间倒回到1天,则下一个计划任务将在5秒+ 1天内运行.

如果您运行下面的脚本,然后几天前更改系统时间,那么您可以重现该问题.该问题可以在Linux和Windows上重现.

import sched
import time
import threading

period = 5
scheduler = sched.scheduler(time.time, time.sleep)

def check_scheduler():
    print time.time()
    scheduler.enter(period, 1, check_scheduler, ())

if __name__ == '__main__':
    print time.time()

    scheduler.enter(period, 1, check_scheduler, ())

    thread = threading.Thread(target=scheduler.run)
    thread.start()
    thread.join()
    exit(0)
Run Code Online (Sandbox Code Playgroud)

任何人都有这个问题的任何python解决方案?

Dan*_*scu 3

计划文档中:

\n\n
\n

sched.scheduler 类(timefunc、delayfunc)

\n\n

调度程序类定义了调度事件的通用接口。它需要两个函数来实际处理 \xe2\x80\x9coutside\n world\xe2\x80\x9d \xe2\x80\x94 timefunc 应该可以不带参数调用,并返回一个\n 数字(\xe2\x80\ x9ctime\xe2\x80\x9d,任何单位)。该delayfunc函数\n应该可以用一个参数调用,与\n timefunc的输出兼容,并且应该延迟那么多的时间单位。每个事件运行后,delayfunc 也将使用参数 0 进行调用,以允许其他线程有机会在多线程应用程序中运行。

\n
\n\n

您遇到的问题是您的代码使用time.time()as timefunc,其返回值(当不带参数调用时)是当前系统时间,因此会受到重新绕系统时钟的影响。

\n\n

为了使您的代码不受系统时间更改的影响,您需要提供一个timefunc不依赖于系统时间、开始/当前时间戳等的代码。

\n\n

您可以编写自己的函数,例如返回自进程启动以来的秒数,您必须在代码中实际计数(即不compute it基于时间戳增量)。如果该time.clock()函数基于 CPU 时间计数器,它可能会有所帮助,但我不确定这是否属实。

\n