在Python中执行计时器函数的正确方法
我有一个GUI应用程序,需要在后台做一些简单的事情(更新wx python进度条,但这并不重要)。我看到有一个threading.timer类。。但似乎没有办法让它重演。因此,如果我使用计时器,我最终不得不在每次执行时创建一个新线程。。。比如:在Python中执行计时器函数的正确方法,python,multithreading,timer,Python,Multithreading,Timer,我有一个GUI应用程序,需要在后台做一些简单的事情(更新wx python进度条,但这并不重要)。我看到有一个threading.timer类。。但似乎没有办法让它重演。因此,如果我使用计时器,我最终不得不在每次执行时创建一个新线程。。。比如: import threading import time def DoTheDew(): print "I did it" t = threading.Timer(1, function=DoTheDew) t.daemon =
import threading
import time
def DoTheDew():
print "I did it"
t = threading.Timer(1, function=DoTheDew)
t.daemon = True
t.start()
if __name__ == '__main__':
t = threading.Timer(1, function=DoTheDew)
t.daemon = True
t.start()
time.sleep(10)
这好像是我在做一堆线,做了一件傻事就死了。。为什么不写为:
import threading
import time
def DoTheDew():
while True:
print "I did it"
time.sleep(1)
if __name__ == '__main__':
t = threading.Thread(target=DoTheDew)
t.daemon = True
t.start()
time.sleep(10)
我是不是错过了让计时器继续工作的方法?这两个选项中的任何一个看起来都很愚蠢。。。我正在寻找一个更像java.util.timer的计时器,它可以安排线程每秒发生一次。。。如果Python中没有一种方法,那么我上面的哪种方法更好?为什么?wxwindows有。它支持一次触发和重复事件。类似的模式可能是您应该做的,但很难说,因为您没有提供太多细节
def do_background_work(self):
# do work on a background thread, posting updates to the
# GUI thread with CallAfter
while True:
# do stuff
wx.CallAfter(self.update_progress, percent_complete)
def update_progress(self, percent_complete):
# update the progress bar from the GUI thread
self.gauge.SetValue(percent_complete)
def on_start_button(self, event):
# start doing background work when the user hits a button
thread = threading.Thread(target=self.do_background_work)
thread.setDaemon(True)
thread.start()
第二种变体有什么问题?这是在Pythonwx.CallAfter、wx.CallLater和wx.Timer中完成任务的标准方法,它们是您的朋友。这更多地是关于wxPython而不是Python本身。你低估了你正在尝试做的事情(更新进度条)的重要性,但你不应该这样做。我只是认为这是一件普通的编程事情。。每X秒我可能想做一些事情。如果第二种方式是正常方式,请冷静。线程。计时器看起来很弱。啊,好主意。解决了我的wx问题,但不是整个python问题。如果问题是您需要在不同的线程中运行它,那么围绕sleep()的循环就没有问题。如果任务很短,我会尽量避免线程,这样就不必担心锁定资源。