Search code examples
pythonpython-2.7python-multithreading

Cancel timer in Python


I am working on timer class in python and wrote a simple test code for the same. My purpose is to print the "hello world" message 10 times and then cancel the timer once the iterations are done. The problem is I am unable to cancel the timer and code seems to print "hello world" infinitely.

Below is my code:

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

I am using Python 2.7 Any help would be highly appreciated


Solution

  • Your problem is you've made another Timer() in if condition and .cancel() it. The following code solves your problem:

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