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

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

概述我正在使用python的sched模块定期运行一个任务,我想我遇到过一个bug.我发现它依赖于运行python脚本的系统的时间.例如,假设我想每5秒运行一次任务.如果我转发系统时间,则计划任务将按预期运行.但是,如果我将系统时间倒回到1天,那么下一个计划任务将在5秒内运行1天.如果您运行下面的脚本,然后几天前更改系统时间,那么您可以重现该问题.该问题可以在L

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

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

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

import schedimport timeimport threadingperiod = 5scheduler = 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,())    thread = threading.Thread(target=scheduler.run)    thread.start()    thread.join()    exit(0)

任何人都有这个问题的任何python解决方案?最佳答案从the sched documentation开始:

class sched.scheduler(timefunc,delayfunc)

The scheduler class defines a generic interface to scheduling events. It needs two functions to actually deal with the “outsIDe
world” — timefunc should be callable without arguments,and return a
number (the “time”,in any units whatsoever). The delayfunc function
should be callable with one argument,compatible with the output of
timefunc,and should delay that many time units. delayfunc will also
be called with the argument 0 after each event is run to allow other
threads an opportunity to run in multi-threaded applications.

您遇到的问题是您的代码使用time.time()作为timefunc,其返回值(在没有参数的情况下调用时)是当前系统时间,因此会受到重新缠绕系统时钟的影响.

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

您可以编写自己的函数,例如,返回自启动过程以来的秒数,您必须在代码中实际计算(即不根据时间戳增量计算它). time.clock()函数可能有帮助,如果它基于cpu时间计数器,但我不确定这是否真实.

总结

以上是内存溢出为你收集整理的如何使用Python安排一个不受系统时间变化影响的周期性任务全部内容,希望文章能够帮你解决如何使用Python安排一个不受系统时间变化影响的周期性任务所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1206403.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-04
下一篇 2022-06-04

发表评论

登录后才能评论

评论列表(0条)

保存