可取消线程。Python中的计时器

2024-06-16 10:52:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试编写一个方法,它会倒计时到给定的时间,除非给出重新启动命令,否则它将执行任务。但我不认为Pythonthreading.Timer类允许取消计时器。

import threading

def countdown(action):
    def printText():
        print 'hello!'

    t = threading.Timer(5.0, printText)
    if (action == 'reset'):
        t.cancel()

    t.start()

我知道上面的代码是错的。希望你能给我一些指导。


Tags: 方法import命令hellodef时间action计时器
3条回答

threading.Timer确实有一个cancel方法,尽管它不会取消线程,但它会停止计时器的实际触发。实际发生的情况是,cancel方法设置了一个threading.Event,而实际执行threading.Timer的线程将在完成等待之后和实际执行回调之前检查该事件。

也就是说,计时器通常是在不使用单独线程的情况下实现的。最好的方法取决于你的程序实际在做什么(在等待这个计时器的时候),但是任何有事件循环的东西,比如GUI和网络框架,都有方法请求一个连接到事件循环的计时器。

启动计时器后将调用cancel方法:

import time
import threading

def hello():
    print "hello, world"
    time.sleep(2)

t = threading.Timer(3.0, hello)
t.start()
var = 'something'
if var == 'something':
    t.cancel()

您可以考虑在Thread上使用while循环,而不是使用计时器
下面是一个从尼古拉斯·格拉德沃尔的answer到另一个问题的例子:

import threading
import time

class TimerClass(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.event = threading.Event()
        self.count = 10

    def run(self):
        while self.count > 0 and not self.event.is_set():
            print self.count
            self.count -= 1
            self.event.wait(1)

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

tmr = TimerClass()
tmr.start()

time.sleep(3)

tmr.stop()

我不确定我是否理解正确。你想在这个例子中写些类似的东西吗?

>>> import threading
>>> t = None
>>> 
>>> def sayHello():
...     global t
...     print "Hello!"
...     t = threading.Timer(0.5, sayHello)
...     t.start()
... 
>>> sayHello()
Hello!
Hello!
Hello!
Hello!
Hello!
>>> t.cancel()
>>>

相关问题 更多 >