Python中可取消的线程.Timer

Ted*_*Ted 34 python timer python-multithreading python-2.7

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

import threading

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

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

    t.start()
Run Code Online (Sandbox Code Playgroud)

我知道上面的代码是错误的.非常感谢这里的一些指导.

Hon*_*Abe 35

您可以在启动计时器后调用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()
Run Code Online (Sandbox Code Playgroud)

您可以考虑在Thread上使用while循环,而不是使用Timer.
以下是Nikolaus Gradwohl 对另一个问题的回答:

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()
Run Code Online (Sandbox Code Playgroud)

  • @WesModes我提供了一个打印倒数的替代方案. (2认同)

Ada*_*dam 13

我不确定我是否理解正确.你想写这个例子中的东西吗?

>>> 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()
>>>
Run Code Online (Sandbox Code Playgroud)


Tho*_*ers 7

threading.Timer确实有一个cancel方法,虽然它不会取消线程,它将从实际射击停止计时器.实际发生的是该cancel方法设置了一个threading.Event,并且实际执行的线程threading.Timer将在它完成等待之后以及它实际执行回调之前检查该事件.

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