Python 线程 - 如何在单独的线程中重复执行函数? [英] 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()
我正在尝试你好,世界!"每秒打印一次,但是当我运行代码时什么也没有发生,这个过程只是保持活动状态.
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.
我对在 python 中设置适当的间隔有多么困难感到非常困惑,因为我已经习惯了 JavaScript.我觉得我错过了什么.
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.
感谢帮助.
推荐答案
我认为您当前的方法没有任何问题.它在 Python 2.7 和 3.4.5 中都对我有用.
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()
打印:
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()
没有对象Timer
类,您必须关闭解释器才能停止线程.
Without having the object to Timer
class, you will have to shut your interpreter in order to stop the thread.
替代方法:
我个人更喜欢通过扩展来编写计时器线程Thread
类为:
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..")
然后用 Event 的对象启动线程
类为:
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..
要停止线程,执行:
my_event.set()
这为将来修改更改提供了更大的灵活性.
This provides more flexibility in modifying the changes for the future.
这篇关于Python 线程 - 如何在单独的线程中重复执行函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!