我有几节课看起来差不多是这样的:import threading
import time
class Foo():
def __init__(self, interval, callbacks):
self.thread = threading.Thread(target=self.loop)
self.interval = interval
self.thread_stop = threading.Event()
self.callbacks = callbacks
def loop():
while not self.thread_stop.is_set():
#do some stuff...
for callback in self.callbacks():
callback()
time.sleep(self.interval)
def start(self):
self.thread.start()
def kill(self):
self.thread_stop.set()
我用的是我的主线:
^{pr2}$
我想要一个键盘中断来杀死线程后,所有的回调已经完成,但在循环重复之前。目前它们被忽略了,我不得不停止运行程序的终端进程。在
我看到了使用线程。事件从this post开始,但似乎我做得不正确,这使得这个项目的工作变得相当麻烦。在
我不知道它是否相关,但是我传递的回调从Internet访问数据,并大量使用重试装饰器来处理不可靠的连接。在
编辑
在这个循环之后,每个人看起来都像是在救命:def thread_loop(self):
while not self.thread_stop.is_set():
# do some stuff
# call the callbacks
self.thread_stop.wait(self.interval)
这是一种解决方案,尽管并不理想。此代码在PythonAnywhere上运行,帐户的价格是按CPU时间计算的。我要看看在一天的时间里,随着线程的不断唤醒和休眠,这个方法使用了多少,但它至少解决了主要问题