Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timer runs only once in python

Tags:

python-3.x

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.

like image 923
Siva Gnanam Avatar asked Apr 14 '26 06:04

Siva Gnanam


1 Answers

(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()
like image 100
Fabrizio A. Avatar answered Apr 17 '26 00:04

Fabrizio A.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!