2

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

3 Answers 3

4

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()
Sign up to request clarification or add additional context in comments.

1 Comment

is return 0, required at the end ?
2

Seems like you start your timer again right after you cancelled it.

If you change your code to return from start_job() when your end-condition is reached it should work.

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

Actually you don't even have to cancel the timer this way, you just don't start a new one, if the condition is reached.

Comments

2

cancelmethod is used to stop the created timer before its action has begun, so just return will be ok.

if self.iteration_count == 10:
    return

See 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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.