Skip to main content
 首页 » 编程设计

python之在 Python 中取消定时器

2025年05月04日14zhwl

我正在使用 python 编写计时器类,并为此编写了一个简单的测试代码。我的目的是打印“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 任何帮助将不胜感激

请您参考如下方法:

您的问题是您在 if 条件和 .cancel() 中创建了另一个 Timer()。以下代码解决了您的问题:

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