我认为您当前的方法没有任何问题。它在 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 https://docs.python.org/2/library/threading.html#timer-objects类中,您将必须关闭解释器才能停止线程。
替代方法:
就我个人而言,我更喜欢通过扩展来编写计时器线程Thread https://docs.python.org/2/library/threading.html#threading.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 https://docs.python.org/2/library/threading.html#threading.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()
这为将来修改更改提供了更大的灵活性。