在Python中取消计时器 [英] Cancel timer in Python

查看:15
本文介绍了在Python中取消计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Python开发Timer类,并为此编写了一个简单的测试代码。我的目的是打印10次"Hello world"消息,然后在迭代完成后取消计时器。问题是我无法取消计时器,代码似乎无限地打印"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()

我正在使用Python2.7 如有任何帮助,我们将不胜感激

推荐答案

试试:

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

[注意]:

您的问题是您在if条件中创建了另一个Timer(),并且.cancel()

这篇关于在Python中取消计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆