3

The following program print hello world only once instead it has to print the string for every 5 seconds.

from threading import Timer;

class TestTimer:

    def __init__(self):
        self.t1 = Timer(5.0, self.foo);

    def startTimer(self):
        self.t1.start();

    def foo(self):
        print("Hello, World!!!");

timer = TestTimer();
timer.startTimer();


                       (program - 1)

But the following program prints the string for every 5 seconds.

def foo():
    print("World");
    Timer(5.0, foo).start();

foo();

                        (program - 2)

Why (program - 1) not printing the string for every 5 seconds ?. And how to make the (program - 1) to print the string for every 5 seconds continuously.

1
  • Why are you wrapping it in an extra class to begin with? Is this necessary? Commented Dec 1, 2016 at 15:29

2 Answers 2

1

(program - 2) prints a string every 5 seconds because it is calling itself recursively. As you can see, you call foo() function inside itself and this is the reason because it works.

If you want to print a string every 5 secs in (program - 1) using a class you could (but it's not really a good practice!):

from threading import Timer

class TestTimer:
    def boo(self):
        print("World")
        Timer(1.0, self.boo).start()

timer = TestTimer()
timer.boo()
Sign up to request clarification or add additional context in comments.

Comments

0

As has been pointed out, you're calling the foo() recursively:

def foo():
    print("World");
    Timer(5.0, foo).start();  # Calls foo() again after 5s and so on

foo();

In your question, you've created a wrapper around threading.Timer - I suggest you simply subclass it:

from threading import Timer

class TestTimer(Timer):

    def __init__(self, i):
        self.running = False
        super(TestTimer, self).__init__(i, self.boo)

    def boo(self):
        print("Hello World")

    def stop():
        self.running = False
        super(TestTimer, self).stop()

    def start():
        self.running = True
        while self.running:
            super(TestTimer, self).start()

t = TestTimer(5)
t.start()

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.