【问题标题】:Getting the time remaining before event.wait is done in Python在 Python 中获取 event.wait 之前的剩余时间
【发布时间】:2012-08-02 19:32:07
【问题描述】:

我正在编写一个 Python 脚本,其中我有一个线程正在运行,它计算一些值并每小时创建一个图表。我想做的是在那个线程中有一个函数,告诉我在下一次更新发生之前还有多少时间。我目前的实现如下:

class StatsUpdater(threading.Thread):

    def __init__(self, updateTime):
        threading.Thread.__init__(self)
        self.event = threading.Event()
        self.updateTime = updateTime

    def run(self):
        while not self.event.is_set():
            self.updateStats()
            self.event.wait(self.updateTime)

    def updateStats(self):
        print "Updating Stats"
        tables = SQLInterface.listTables()

        for table in tables:
            PlotTools.createAndSave(table)

    def stop(self):
        self.event.set()

所以我想要在该类中添加另一个函数,让我返回剩余时间 gefore self.event.wait(self.updateTime) 超时,如下所示:

def getTimeout(self):
    return self.event.timeRemaining()

这有可能吗?

【问题讨论】:

    标签: python multithreading timer timeout


    【解决方案1】:

    不支持直接获取剩余时间,但您可以睡几次并跟踪剩余时间。

    def __init__(self, updateTime):
        threading.Thread.__init__(self)
        self.event = threading.Event()
        self.updateTime = updateTime
        self.wait_time=None
    
    def run(self):
        while not self.event.is_set():
            self.updateStats()
            try:
                self.wait_time=self.updateTime
                inttime=int(self.updateTime)
                remaining=inttime-self.updateTime
                self.event.wait(remaining)
                for t in reversed(range(inttime)): 
                    self.wait_time=t+1
                    self.event.wait(1)
            finally:
                self.wait_time=0
    

    然后使用

    def getTimeout(self):
        return self.wait_time
    

    【讨论】:

    • 是的,我自己也是这么想的,不过还是感谢您的反馈。问题是这个程序在 Raspberry Pi 上运行(如果你听说过,不知道)所以我的资源非常少,我担心必须每秒执行 wait_time=t+1 会消耗很多时间/资源系统。还有其他方法可以实现吗?如果没有,我宁愿保持现在的状态,在下一次更新之前能够读取时间是一种奢侈,而不是必须的。
    • 试试吧。也许它很慢,但我怀疑你会注意到。您还可以将睡眠时间更改为 5 秒。
    【解决方案2】:

    好的,我对我的问题有一个妥协。我在 StatsUpdater.run 中实现了一个变量:

    self.lastUpdateTime = int(time.time())
    

    就在我执行更新功能之前。

    现在当我调用 getTimeout() 时,我会这样做:

    def getTimeout(self):
        timePassed = int(time.time() - self.lastUpdateTime
        return self.updateTime - timePassed
    

    这样,我没有计算密集型线程运行和计算 每秒一小笔钱,但我仍然可以很好地指示下一次更新的时间,因为更新之间的时间量也是已知的;)

    【讨论】:

    • 感谢您的帮助,我在阅读您的回复时得到了想法;)
    猜你喜欢
    • 1970-01-01
    • 2013-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-01
    • 1970-01-01
    • 2015-03-22
    相关资源
    最近更新 更多