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.
(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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With