代码之家  ›  专栏  ›  技术社区  ›  stefan.stt

如何停止循环线程

  •  0
  • stefan.stt  · 技术社区  · 6 年前

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

    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 回复  |  直到 6 年前
        1
  •  0
  •   dim    6 年前

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