0

I'm writing a Python script in which i have a thread running that calculates some values and creates a graph every hour. What I would like to do is have a function in that thread that tells me how much time there is remaining before the next update happens. My current implementation is as follows:

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()

So what i would like is adding another function in that class that gives me back the time remaining gefore self.event.wait(self.updateTime) times out, something like this:

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

Is this possible somehow?

4

2 回答 2

1

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

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

在我执行更新功能之前。

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

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

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

于 2012-08-05T20:33:39.133 回答
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
于 2012-08-05T16:49:47.007 回答