Python Threading - How To Repeatedly Execute A Function In A Separate Thread?
Solution 1:
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
defprintit():
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
classMyThread(Thread):
def__init__(self, event):
Thread.__init__(self)
self.stopped = event
defrun(self):
whilenot 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.
Solution 2:
I run it in python 3.6.It works ok as you expected .
Solution 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:
from threading import Thread,Event
from time import sleep
defthreaded_function(evt):
whileTrue: # ie runs foreverif evt.isSet():
return()
print"running"
sleep(1)
if __name__ == "__main__":
e=Event()
thread = Thread(target = threaded_function, args = (e, ))
thread.start()
sleep(5)
e.set() # tells the thread to exit
thread.join()
print"thread finished...exiting"
Solution 4:
I have used Python 3.6.0. And I have used _thread and time package.
import time
import _thread as t
defa(nothing=0):
print('hi',nothing)
time.sleep(1)
t.start_new_thread(a,(nothing+1,))
t.start_new_thread(a,(1,))#first argument function name and second argument is tuple as a parameterlist.
o/p will be like hi 1 hi 2 hi 3 ....
Post a Comment for "Python Threading - How To Repeatedly Execute A Function In A Separate Thread?"