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.
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.
which prints:
But I'll suggest to start the thread as:
So that you can stop the thread using:
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:Then start thread with object of
Event
class as:You'll start seeing the below output in the screen:
To stop the thread, execute:
This provides more flexibility in modifying the changes for the future.
I run it in python 3.6.It works ok as you expected .
Try this:
I have used Python 3.6.0.
And I have used _thread and time package.
o/p will be like
hi 1
hi 2
hi 3
....
What might be an issue is that you are creating a new thread each time you are running printit.
A better way may be just to create one thread that does whatever you want it to do and then you send and event to stop it when it is finished for some reason: