启动同一线程两次

时间:2018-08-17 12:02:12

标签: python-2.7 python-multithreading

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

    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)

1 个答案:

答案 0 :(得分:1)

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

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>name</p>
<input type="text" id='nama'>
<span id='namaspan' class='error-span'>name cannot be empty</span>
<br>
<p>number</p>
<input type="text" id='nomor'>
<span id='nomorspan' class='error-span'>number cannot be empty</span>

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

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