在Python中取消计时器

时间:2018-10-25 08:52:46

标签: python python-2.7 python-multithreading

我正在python中使用计时器类,并为此编写了一个简单的测试代码。我的目的是打印“ hello world”消息10次,然后在完成迭代后取消计时器。问题是我无法取消计时器,并且代码似乎可以无限打印“ hello world”。

下面是我的代码:

createUser()

我正在使用Python 2.7 任何帮助将不胜感激

3 个答案:

答案 0 :(得分:2)

似乎您在取消计时器后立即重新启动计时器。

如果将代码更改为在达到最终条件时从start_job()返回,则代码应该可以正常工作。

    if self.iteration_count == 10:
        Timer(self.heartbeat, self.start_job, ()).cancel()
        return

实际上,您甚至不必以这种方式取消计时器,只要满足条件,您就不必重新启动计时器。

答案 1 :(得分:2)

尝试一下:

from threading import Timer

class MyClass(object):
    def __init__(self):
        self.iteration_count = 0
        self.heartbeat = 1

    @staticmethod
    def print_msg():
        print "hello world!"

    def start_job(self):
        self.print_msg()
        self.iteration_count += 1

        timer = Timer(
            interval=self.heartbeat,
            function=self.start_job,
        )
        timer.start()

        if self.iteration_count >= 10:
            timer.cancel()

MyClass().start_job()

[注意]:

您的问题是您在Timer()状态下又创建了一个if,并且.cancel()

答案 2 :(得分:2)

cancel方法用于在动作开始之前停止所创建的计时器,因此return就可以了。

if self.iteration_count == 10:
    return

请参见Timer Objects

  

可以通过调用cancel()方法来停止计时器(在其动作开始之前)。

def hello(): 
    print "hello, world"

t = Timer(30.0, hello)
t.start() # will print "hello, world" after 30 seconds

t.cancel() # stop it printing "hello, world"