如何停止循环线

时间:2018-08-17 08:48:33

标签: multithreading python-2.7

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

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)

1 个答案:

答案 0 :(得分:0)

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