2013-03-05 92 views
3

我正在製作一個wxPython應用程序,我需要每15秒更新一次互聯網上的值。有沒有什麼辦法可以讓我設置一個函數來設置這個值,並且讓它在這個間隔下運行,而不會中斷程序?以間隔重複功能?

編輯:這裏就是我想:

import thread 

class UpdateThread(Thread): 
    def __init__(self): 
     self.stopped = False 
     UpdateThread.__init__(self) 
    def run(self): 
     while not self.stopped: 
      downloadValue() 
      time.sleep(15) 
def downloadValue(): 
    print x 

UpdateThread.__init__() 

回答

2

你想要什麼是添加在指定的速度運行,你的任務的線程。

您可以在這裏看看這個好的答案:https://stackoverflow.com/a/12435256/667433可以幫助您實現這一目標。

編輯:這是應該爲你工作的代碼:

import time 
from threading import Thread # This is the right package name 

class UpdateThread(Thread): 
    def __init__(self): 
     self.stopped = False 
     Thread.__init__(self) # Call the super construcor (Thread's one) 
    def run(self): 
     while not self.stopped: 
      self.downloadValue() 
      time.sleep(15) 
    def downloadValue(self): 
     print "Hello" 

myThread = UpdateThread() 
myThread.start() 

for i in range(10): 
    print "MainThread" 
    time.sleep(2) 

希望它可以幫助

+0

所以我做了這個類,那麼如何開始呢?我得到'NameError:名字'線'未定義'當我啓動它。 – tkbx 2013-03-05 13:56:08

+0

您可能需要在您的源代碼中導入線程代碼 – 2013-03-05 13:57:47

+0

我將編輯我的答案以顯示我的代碼,但無法使其工作。 – tkbx 2013-03-05 14:01:00

0

我都做過類似的東西,這一點:

- 你需要一個線程來在後臺運行。

- 和一個定義了「自定義」事件,以便在需要

當創建自定義的WX事件

(MyEVENT_CHECKSERVER, EVT_MYEVENT_CHECKSERVER) = wx.lib.newevent.NewEvent()

在UI「初始化」胎面可以通知UI可以綁定事件,並啓動線程

# bind the custom event 
    self.Bind(EVT_MYEVENT_CHECKSERVER, self.foo) 
    # and start the worker thread 
    checkServerThread = threading.Thread(target=worker_checkServerStatus 
             ,args=(self,)) 
    checkServerThread.daemon = True 
    checkServerThread.start() 

工作線程可以是這樣的事情,PS。來電者是UI實例

def worker_checkServerStatus(caller):

while True:  
     # check the internet code here 
     evt = MyEVENT_CHECKSERVER(status='Some internet Status') #make a new event 
     wx.PostEvent(caller, evt) # send the event to the UI 
     time.sleep(15) #ZZZzz for a bit 

編輯:小姐閱讀問題...