加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-16 22:49:41 所属栏目:Python 来源:网络整理
导读:我正在使用python的sched模块定期运行一个任务,我想我遇到过一个bug. 我发现它依赖于运行python脚本的系统的时间.例如,假设我想每5秒运行一次任务.如果我转发系统时间,则计划任务将按预期运行.但是,如果我将系统时间倒回到1天,那么下一个计划任务将在5秒内运

我正在使用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,())

    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时间计数器,但我不确定这是否真实.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读