首页 > 解决方案 > 如何停止循环线程

问题描述

我有一个这样的循环线程方法:

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)

标签: multithreadingpython-2.7

解决方案


尝试在字典中为每个计时器保留一个参考:my_dict["method_name"] = timer. 在这种情况下,当您决定停止计时器时,只需调用my_dict["method_name"].cancel().


推荐阅读