Search code examples
pythonmultithreadingtimersetinterval

Python threading - How to repeatedly execute a function in a separate thread?


I have this code:

import threading
def printit():
  print ("Hello, World!")
  threading.Timer(1.0, printit).start()
threading.Timer(1.0, printit).start()

I am trying to have "Hello, World!" printed every second, however when I run the code nothing happens, the process is just kept alive.

I have read posts where exactly this code worked for people.

I am very confused by how hard it is to set a proper interval in python, since I'm used to JavaScript. I feel like I'm missing something.

Help is appreciated.


Solution

  • I don't see any issue with your current approach. It is working for me me in both Python 2.7 and 3.4.5.

    import threading
    
    def printit():
        print ("Hello, World!")
        # threading.Timer(1.0, printit).start()
        #  ^ why you need this? However it works with it too
    
    threading.Timer(1.0, printit).start()
    

    which prints:

    Hello, World!
    Hello, World!
    

    But I'll suggest to start the thread as:

    thread = threading.Timer(1.0, printit)
    thread.start()
    

    So that you can stop the thread using:

    thread.cancel()
    

    Without having the object to Timer class, you will have to shut your interpreter in order to stop the thread.


    Alternate Approach:

    Personally I prefer to write a timer thread by extending Thread class as:

    from threading import Thread, Event
    
    class MyThread(Thread):
        def __init__(self, event):
            Thread.__init__(self)
            self.stopped = event
    
        def run(self):
            while not self.stopped.wait(0.5):
                print("Thread is running..")
    

    Then start thread with object of Event class as:

    my_event = Event()
    thread = MyThread(my_event)
    thread.start()
    

    You'll start seeing the below output in the screen:

    Thread is running..
    Thread is running..
    Thread is running..
    Thread is running..
    

    To stop the thread, execute:

    my_event.set()
    

    This provides more flexibility in modifying the changes for the future.