Search code examples
pythonmultithreadingtimer

How can I make this timer run forever?


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()

Solution

  • 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.