如何暂停和恢复Python threading.Timer

时间:2015-05-01 03:55:24

标签: python multithreading timer

在python中,threading.Timer可以在一段时间后执行函数。但没有暂停或恢复功能。还有其他办法吗?

需要这样的东西。

from threading import Timer
from time import sleep
def Hello():
    print "hello"
t=Timer(10, Hello)
t.start()
sleep(3)
### <Pause Timer t>
### <do some work>
### <Resume Timer t>

如果知道Timer启动了多长时间或剩余多少时间,也会有所帮助。所以上面可以这样做:

### x =  Time passed by Timer t
### t.cancel()
### <do some work>
### t=Timer(10-x, Hello)
### t.start()

修改1:

这是我在vitaut回答后的代码:

## My Timer Class ##

from threading import Timer as threadTimer
from time import time, sleep
from random import randint as rint

class MyTimer:

    def __init__(self, key, delete):
        self.startTime = time()
        self.timer = threadTimer(15, delete, args=[key])
        self.timer.start()
    def pause(self):
        self.timer.cancel()
        self.endTime = time()
    def resume(self, delete, key):
        self.timer = threadTimer(15-(self.endTime-self.startTime), delete, args=[key])
        self.timer.start()
    def cancel(self):
        self.timer.cancel()

我正在使用此代码进行测试:

class MyClass:

    def __init__(self):
        self.dict={}

    def delete(self, key):
        print key, time()-self.dict[key]["stime"]
        self.dict[key]["timer"]=None
        self.dict[key]=None
        del self.dict[key]

    def doSomeWork(self, key):
        for i in xrange(10):
            x=str(rint(0,3))
            if self.dict.has_key(key):
                self.dict[key]["timer"].pause()
                print key,
                sleep(1)
                self.dict[key]["timer"].resume(self.delete, key)
        print

    def createDict(self):
        print "Pausing Timer for 1 second for ",
        for i in xrange(10):
            self.dict[i]={}
            self.dict[i]["timer"]=MyTimer(key, self.delete)
            self.dict[i]["stime"]=time()

x=MyClass()
x.createDict()
x.doSomeWork()

输出:

Pausing Timer for 1 second for  0 1 0 2 1 0 2 1 1 0
3 15.0000641346
4 15.0000319481
5 15.0000360012
6 15.0000460148
7 15.0002529621
8 15.0000050068
9 15.0001029968
0 16.000754118
2 16.0007479191
1 16.0011930466

因为它将定时器与键1暂停4次,持续1秒。所以1的最终时间应该是19+秒(预期)。但它只显示了16个。

1 个答案:

答案 0 :(得分:2)

AFAIK Timer类没有暂停/恢复功能,但您可以使用start / cancel轻松模拟它,并跟踪自己启动计时器的时间。