[英]Python threading - How to repeatedly execute a function in a separate thread?
我有這段代碼:
import threading
def printit():
print ("Hello, World!")
threading.Timer(1.0, printit).start()
threading.Timer(1.0, printit).start()
我試圖每秒打印一次“Hello, World”,但是當我運行代碼時什么也沒有發生。 這個過程只是保持活力。
我讀過一些帖子,其中正是這段代碼對人們有用。
我很困惑在python中設置一個合適的間隔有多難,因為我已經習慣了JavaScript。我覺得我錯過了什么。
感謝幫助。
我認為您目前的方法沒有任何問題。 它在Python 2.7和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()
打印:
Hello, World!
Hello, World!
但我建議以如下方式啟動線程:
thread = threading.Timer(1.0, printit)
thread.start()
這樣您就可以使用以下命令停止線程:
thread.cancel()
如果沒有Timer
類的對象,則必須關閉解釋器才能停止線程。
替代方法:
我個人更喜歡通過將Thread
類擴展為來編寫計時器線程:
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..")
然后使用Event
類的對象啟動線程,如下所示:
my_event = Event()
thread = MyThread(my_event)
thread.start()
您將開始在屏幕上看到以下輸出:
Thread is running..
Thread is running..
Thread is running..
Thread is running..
要停止線程,執行:
my_event.set()
這為將來的更改提供了更大的靈活性。
我在python 3.6中運行它。
嘗試這個:
import time
def display():
for i in range(1,5):
time.sleep(1)
print("hello world")
我使用過Python 3.6.0。
而且我使用了_thread和time包。
import time
import _thread as t
def a(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會像
嗨1
嗨2
嗨3
....
可能的問題是,每次運行printit時都在創建一個新線程。
更好的方法可能是創建一個線程,該線程可以執行您想要執行的任何操作,然后出於某種原因發送並發送事件以使其停止運行:
from threading import Thread,Event
from time import sleep
def threaded_function(evt):
while True: # ie runs forever
if 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"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.