简体   繁体   中英

How to pause and resume Python threading.Timer

In python, threading.Timer works fine to execute a function after sometime. But there is no pause or resume feature. Is there any other way to do it?

Something like this is required.

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>

It would also be helpful if it is known for how much time the Timer has started or how much time is left. So the above can be done something like this:

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

Edit 1:

This is my code after the answer by 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()

I'm using this code for testing:

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

The Output:

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

Since it's pausing the Timer with key 1 for 4 times each for 1 seconds. So the final time for 1 should be 19+ seconds (Expected). But it's showing 16 only.

AFAIK Timer类没有暂停/继续功能,但是您可以通过start / cancel轻松地模拟它,并跟踪自己启动计时器的时间。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM