简体   繁体   English

在Python中执行计时器功能的正确方法

[英]Correct way to do timer function in Python

I have a GUI application that needs to do something simple in the background (update a wx python progress bar, but that doesn't really matter). 我有一个GUI应用程序,需要在后台做一些简单的事情(更新wx python进度条,但这并不重要)。 I see that there is a threading.timer class.. but there seems to be no way to make it repeat. 我看到有一个threading.timer类。但是似乎没有办法使它重复。 So if I use the timer, I end up having to make a new thread on every single execution... like : 因此,如果使用计时器,则最终必须在每次执行时都创建一个新线程……

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)

This seems like I am making a bunch of threads that do 1 silly thing and die.. why not write it as : 好像我在做一堆线程,这些线程会做1愚蠢的事而死..为什么不这样写:

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)

Am I missing some way to make a timer keep doing something? 我是否缺少使计时器继续执行某些操作的方法? Either of these options seems silly... I am looking for a timer more like a java.util.Timer that can schedule the thread to happen every second... If there isn't a way in Python, which of my above methods is better and why? 这些选项中的任何一个似乎都是愚蠢的...我正在寻找一个更像java.util.Timer的计时器,该计时器可以安排线程每秒发生一次...如果Python中没有办法,那么我上面的哪种方法更好,为什么?

A pattern more like this is probably what you should be doing, but it's hard to say because you didn't provide many details. 像这样的模式可能是您应该做的,但是很难说,因为您没有提供很多细节。

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()

wxwindows has its own timer . wxwindows有其自己的计时器 It supports one shot, and reoccurring events. 它支持一次拍摄和重复发生的事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM