我正在创建一个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__()
答案 0 :(得分: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)
希望有所帮助
答案 1 :(得分:0)
我做了类似的事情:
- 你需要一个线程在后台运行。
- 定义'自定义'事件,以便胎面可以在需要时通知用户界面
创建自定义WX事件
(MyEVENT_CHECKSERVER,EVT_MYEVENT_CHECKSERVER)= wx.lib.newevent.NewEvent()
在UI“ init ”上,您可以绑定事件,并启动线程
# 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(来电者):
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
编辑:小姐阅读问题...
答案 2 :(得分:0)
另一种方法是使用计时器:
import threading
stopNow = 0
def downloadValue():
print("Running downloadValue")
if not stopNow: threading.Timer(15,downloadValue).start()
downloadValue()
这是重复函数的经典模式:函数本身向其自身添加了定时调用。要开始循环,请调用函数(它会立即返回)。要中断循环,请将stopNow设置为1。