在Python中正确使用定时器函数的方法

2 投票
2 回答
6728 浏览
提问于 2025-04-15 23:08

我有一个图形界面应用程序,需要在后台做一些简单的事情(比如更新一个wx python的进度条,不过这不太重要)。我发现有一个叫做threading.timer的类,但似乎没有办法让它重复执行。所以如果我使用这个定时器,每次执行的时候都得新建一个线程…就像这样:

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里没有这种方法,那我上面提到的哪种方式更好,为什么呢?

2 个回答

3

你可能应该采用更像这样的模式,但很难确定,因为你没有提供很多细节。

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

wxwindows 有一个自己的定时器。这个定时器可以设置一次性事件,也可以设置重复发生的事件。

撰写回答