from threading import Timer
def hello():
    print "hello, world"
t = Timer(30.0, hello)
t.start()
This code only fires the timer once.
How can I make the timer run forever?
Thanks,
updated
this is right :
import time,sys
def hello():
    while True:
        print "Hello, Word!"
        sys.stdout.flush()
        time.sleep(2.0)
hello()
and this:
from threading import Timer
def hello():
    print "hello, world"
    sys.stdout.flush()
    t = Timer(2.0, hello)
    t.start()
t = Timer(2.0, hello)
t.start()
                A threading.Timer executes a function once.  That function can "run forever" if you wish, for example:
import time
def hello():
    while True:
        print "Hello, Word!"
        time.sleep(30.0)
Using multiple Timer instances would consume substantial resources with no real added value. If you want to be non-invasive to the function you're repeating every 30 seconds, a simple way would be:
import time
def makerepeater(delay, fun, *a, **k):
    def wrapper(*a, **k):
        while True:
            fun(*a, **k)
            time.sleep(delay)
    return wrapper
and then schedule makerepeater(30, hello) instead of hello.
For more sophisticated operations, I recommend standard library module sched.
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