具有按需触发器的周期性Python线程
我有一个简单的PyGTK应用程序。由于我必须运行多个定期任务来获取一些数据并刷新GUI,因此我对线程进行了如下扩展:具有按需触发器的周期性Python线程,python,multithreading,pygtk,task,python-multithreading,Python,Multithreading,Pygtk,Task,Python Multithreading,我有一个简单的PyGTK应用程序。由于我必须运行多个定期任务来获取一些数据并刷新GUI,因此我对线程进行了如下扩展: class MyThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.setDaemon(True) self.event = threading.Event() self.even
class MyThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.setDaemon(True)
self.event = threading.Event()
self.event.set()
def run(self):
while self.event.is_set():
timer = threading.Timer(60, self._run)
timer.start()
timer.join()
def cancel(self):
self.event.clear()
def _run(self):
gtk.threads_enter()
# do what need to be done, fetch data, update GUI
gtk.threads_leave()
我在应用程序引导上启动线程,将它们保存在一些列表中,并在退出之前取消它们。这真是太好了
但现在我想添加刷新按钮,它将强制其中一个线程立即运行,而不是等待一段时间来运行(如果当前未运行)
我试图通过在MyThread中添加bool var来指示线程是否正在运行,然后在运行前重置完成,然后调用MyThread。如果没有运行,请运行,但这会导致我的应用程序变得无响应,并且运行任务永远无法完成执行
我不知道为什么会这样。解决这个问题的最好办法是什么?如果我可以让刷新在后台运行,这样它就不会阻塞GUI,那也没关系
也许要调用run并将秒数传递到1,以便计时器可以更快地触发它?使用另一个事件对象和超时,而不是使用计时器。然后可以从按钮回调中设置该事件。下面的代码说明了这一点,我去掉了您的取消代码以保持简短:
import threading
class MyThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.sleep_event = threading.Event()
self.damon = True
def run(self):
while True:
self.sleep_event.clear()
self.sleep_event.wait(60)
threading.Thread(target=self._run).start()
def _run(self):
print "run"
my_thread = MyThread()
my_thread.start()
while True:
raw_input("Hit ENTER to force execution\n")
my_thread.sleep_event.set()
默认情况下,每60秒打印一次运行。如果按ENTER键,它将立即打印,然后在60秒后再次打印,以此类推。使用另一个事件对象和超时,而不是使用计时器。然后可以从按钮回调中设置该事件。下面的代码说明了这一点,我去掉了您的取消代码以保持简短:
import threading
class MyThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.sleep_event = threading.Event()
self.damon = True
def run(self):
while True:
self.sleep_event.clear()
self.sleep_event.wait(60)
threading.Thread(target=self._run).start()
def _run(self):
print "run"
my_thread = MyThread()
my_thread.start()
while True:
raw_input("Hit ENTER to force execution\n")
my_thread.sleep_event.set()
默认情况下,每60秒打印一次运行。如果按ENTER键,将立即打印,然后在60秒后再次打印,以此类推。谢谢!那正是我想要的。谢谢!这正是我想要的。