multithreading - 如何停止循环线程
问题描述
我有一个这样的循环线程方法:
def make_periodic(self, method, period_sec, *args):
method(*args)
parameters = [method, period_sec] + list(args)
threading.Timer(period_sec, self.make_periodic, parameters).start()
停止一种方法循环的最佳方法是什么?
例如:
import threading
class TestThreading:
PERIOD = 5
def __init__(self):
self.number = 0
self.text = "t"
def method_1(self):
print self.number
self.number += 1
def method_2(self, text):
print self.text
self.text += text
def make_periodic(self, method, period_sec, *args):
method(*args)
parameters = [method, period_sec] + list(args)
threading.Timer(period_sec, self.make_periodic, parameters).start()
if __name__ == '__main__':
test = TestThreading()
test.make_periodic(test.method_1, TestThreading.PERIOD)
test.make_periodic(test.method_2, TestThreading.PERIOD, "t")
# stops the cycling of method_2, but the method_1 continues
test.stop_threading(test.method_2)
解决方案
尝试在字典中为每个计时器保留一个参考:my_dict["method_name"] = timer
. 在这种情况下,当您决定停止计时器时,只需调用my_dict["method_name"].cancel()
.
推荐阅读
- python - 在特定配置文件中打开 selenium Chrome 网络驱动程序后 Python 脚本崩溃
- api - 如何将搜索参数放入获取 youtube api
- c# - 在c#中实现接口时如何访问父类的属性?
- imagemagick - Imagemagick 转换:-剥离所有内容*除了*颜色配置文件(颜色颜色配置文件)
- python - 我如何将此命令嵌入?
- r - 对 R 中的不平衡数据集进行逻辑回归
- angular-material2 - Angular Material 表抛出 nativeElement undefined
- haskell - 如何从 UTCTime 中增加或减少 n 天?
- node.js - node.js exec 命令引用
- amazon-web-services - 在 AWS Glue 作业中处理加密的 JSON