2013-03-05 94 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 

编辑:小姐阅读问题...