2010-05-25 92 views
1

我有一個GUI應用程序需要在後臺執行簡單的操作(更新一個wx python進度條,但這並不重要)。我看到有一個threading.timer類..但似乎沒有辦法讓它重複。所以,如果我使用定時器,我最終不得不做出的每一個執行一個新的線程...,如:在Python中執行計時器功能的正確方法

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) 

這似乎是我作出了一堆做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) 

我錯過了一些方法來讓計時器繼續做些什麼?這些選項中的任何一個看起來都很愚蠢......我正在尋找一個更類似於java.util.Timer的計時器,它可以安排線程每秒發生一次......如果Python中沒有辦法,我的上述哪些方法更好,爲什麼?

+0

第二個變體有什麼問題?這是一個標準的方式來完成你的任務在Python – nkrkv 2010-05-25 16:36:42

+1

wx.CallAfter,wx.CallLater和wx.Timer是你的朋友。 – FogleBird 2010-05-25 16:44:59

+0

這比wxPython更多的是Python本身。你淡化了你想要做什麼(更新進度條)的意義,但你不應該這樣做。 – FogleBird 2010-05-25 16:46:22

回答

2

wxwindows有its own timer。它支持一次鏡頭和重複發生的事件。

+0

啊好的電話。解決我的wx問題,但不是我的整體python問題。 – bwawok 2010-05-25 16:52:26

+0

如果問題是你需要在不同的線程中運行它,那麼sleep()周圍沒有什麼問題。如果任務很短,我會盡量避免線程,這樣我就不必擔心鎖定資源。 – 2010-05-25 16:58:42

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() 
相關問題