在 Python 中取消计时器

Cancel timer in Python

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

下面是我的代码:

from threading import Timer

class myclass():
    iteration_count = 0
    heartbeat = 1

    def printMsg(self):
        print "hello world!"

    def start_job(self):

        self.printMsg()

        self.iteration_count = self.iteration_count + 1

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

        Timer(self.heartbeat, self.start_job, ()).start()


m = myclass()
m.start_job()

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

您似乎在取消计时器后立即再次启动它。

如果您在达到结束条件时将代码从 start_job() 更改为 return,它应该可以工作。

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

实际上你甚至不必通过这种方式取消计时器,如果达到条件,你只是不开始一个新的计时器。

您的问题是您在 if 条件下制作了另一个 Timer() 并且 .cancel() 它。以下代码解决了您的问题:

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

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

if self.iteration_count == 10:
    return

Timer Objects

The timer can be stopped (before its action has begun) by calling the cancel() method.

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"