首页 > 解决方案 > 两次启动同一个线程

问题描述

我想启动同一个计时器两次,这样我就可以停止同一个计时器。当我尝试这个时:

    thread = threading.Timer(period_sec, method, list(args))
    thread.start()
    thread.join()
    thread.start()

我明白RuntimeError: threads can only be started once 了有没有办法这样做?

已编辑

我想创建一个重复计时器。我需要使用同一个线程,这样我才能调用cancel同一个注册线程。这是示例代码:

class TestThreading:
    def __init__(self):
        self.number = 0
        self.text = "t"

        self.threads = dict()
        self.thread_id = 1

    def method_1(self):
        print self.number
        self.number += 1

    def method_2(self, text):
        print self.text
        self.text += text

    def register_periodic_thread(self, method, period_sec, *args):
        thread_name = method.__name__ + "_" + str(self.thread_id)
        current_thread = threading.Timer(period_sec, method, list(args))
        current_thread.run()
        self.thread_id += 1
        self.threads[thread_name] = current_thread
        return thread_name

    def start_periodic_thread(self, thread):
        print thread
        thread.start()
        thread.join()
        print thread

    def stop_periodic_thread(self, thread):
        thread.cancel()

    def get_periodic_thread(self, thread_mame):
        if thread_mame in self.threads:
            return self.threads[thread_mame]

if __name__ == '__main__':
    test = TestThreading()
    task_id = test.register_periodic_thread(test.method_1, 1)
    task = test.get_periodic_thread(task_id)
    test.start_periodic_thread(task)

    import time
    time.sleep(5)
    test.stop_periodic_thread(task)

标签: python-2.7python-multithreading

解决方案


我会使用委托,因为 python 似乎没有默认实现。

from threading import Timer
import time

class RepeatingTimer:
    def __init__(self, period, method, args):
        self.stopped = False
        self.args = args
        self.method = method
        self.period = period
        self.task = None

    def schedule(self):
        if not self.stopped:
            self.task = Timer(self.period, self.run, [])
            self.task.start()
    def run(self):
        if not self.stopped:
            self.method(*self.args)
            self.schedule()
    def stop(self):
        self.stopped = True
        if self.task:
            self.task.cancel()
            self.task.join()

    def start(self):
        self.schedule()

def something(a, b):
    print(a + b)

timmy = RepeatingTimer(0.5, something, (5,6))
timmy.start()

time.sleep(1)
timmy.stop()

这样,在任务结束时,一个新任务就是调度。除非计时器已停止。

此外,它可以被安排以便可以重新启动。


推荐阅读