我正在制作一个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__()发布于 2013-03-05 21:47:19
您想要的是添加一个以指定速度运行任务的线程。
你可能会在这里看到这个很好的答案: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)希望能有所帮助
发布于 2013-03-05 22:16:56
我做了一些类似的东西:
-you需要一个线程在后台运行。
-And a定义一个‘自定义’事件,以便踏步可以在需要时通知UI
创建自定义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。caller是UI实例
定义worker_checkServerStatus(调用者):
而True:#检查此处的互联网代码evt =MyEVENT_CHECKSERVER(wx.PostEvent=‘一些互联网状态’)#创建一个新的事件调用者(caller,evt) #将事件发送到UI time.sleep(15) #ZZZzz等待一段时间
编辑:未读到问题...
发布于 2019-01-14 03:41:55
另一种方法是使用计时器:
import threading
stopNow = 0
def downloadValue():
print("Running downloadValue")
if not stopNow: threading.Timer(15,downloadValue).start()
downloadValue()这是重复函数的经典模式:函数本身向自身添加一个定时调用。要启动循环,请调用函数(它会立即返回)。要中断循环,请将stopNow设置为1。
https://stackoverflow.com/questions/15225252
复制相似问题