python-2.7 - 两次启动同一个线程
问题描述
我想启动同一个计时器两次,这样我就可以停止同一个计时器。当我尝试这个时:
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 似乎没有默认实现。
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()
这样,在任务结束时,一个新任务就是调度。除非计时器已停止。
此外,它可以被安排以便可以重新启动。
推荐阅读
- javascript - 如何从 javascript 的下拉列表中验证 DOB?
- reactjs - 在页面组件的 getInitialProps 中通过 fetch 在接收到的页面之间传递数据
- moment-timezone - 如何清除与时刻时区对象关联的时区
- arm - OpenOCD 执行 MI 命令失败:-target-select remote localhost:3333
- c# - 有没有办法使用 Roslyn 中的 Compilation 对象从引用的程序集中获取程序集级属性?
- python - Python - 很难理解这个递归代码示例
- tsql - 是否有使用 FIFO 分配查询发票和接收的 SQL 语句
- javascript - 如何使用 ChartJS 获取一组 Date 对象并根据一天中的时间显示频率
- scala - 读取文件,控制台没有输出(intellij)
- python - ValueError:密集层的输入0与层不兼容::预期的min_ndim = 2,发现ndim = 1。收到的完整形状:[无]