简体   繁体   English

如何暂停和恢复Python线程

[英]How to pause and resume Python threading.Timer

In python, threading.Timer works fine to execute a function after sometime. 在python中, threading.Timer可以在一段时间后正常执行函数。 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: 编辑1:

This is my code after the answer by vitaut: 这是我在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. 由于它会用键1暂停Timer每次4次,持续1秒。 So the final time for 1 should be 19+ seconds (Expected). 因此,1的最终时间应为19+秒(预期)。 But it's showing 16 only. 但是它只显示16。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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