【发布时间】:2016-05-13 11:28:32
【问题描述】:
在我的 python 项目中,有一个“永远”运行的计时器。 这是计时器的代码:
class MyTimer:
def __init__(self, tempo, target, args= [], kwargs={}):
self._target = target
self._args = args
self._kwargs = kwargs
self._tempo = tempo
def _run(self):
self._timer = threading.Timer(self._tempo, self._run)
self._timer.start()
self._target(*self._args, **self._kwargs)
if globalVar.Flag_Stop_Timer==100:
self._timer.cancel()
def start(self):
self._timer = threading.Timer(self._tempo, self._run)
self._timer.start()
def stop(self):
self._timer.cancel()
计时器调用的函数正在通过 snap7 python“库”在 PLC 中读取数据
问题是似乎每个定时器事件都会生成一个线程。 因为当我得到 370(它是可重复的)事件时,我得到了错误:
线程 Thread-370 中的异常:回溯(最后一次调用):
文件“/usr/lib/python2.7/threading.py”,第 810 行,在 __bootstrap_inner self.run() 文件“/usr/lib/python2.7/threading.py”,第 1082 行,运行中 self.function(*self.args, **self.kwargs) 文件“Main.py”,第 83 行,在 _run self._timer.start() 文件“/usr/lib/python2.7/threading.py”,第 745 行,开始 _start_new_thread(self.__bootstrap, ()) 错误:无法启动新线程
所以我的问题是,只有在前一个事件完成时,我才能确保触发一个新的计时器事件?或类似的东西......
-------------第一次编辑 ------
@J.F. 的第一条评论塞巴斯蒂安我用这个:
def call_repeatedly(interval, func, *args):
stopped = Event()
def loop():
while not stopped.wait(interval): # the first call is in `interval` secs
func(*args)
Thread(target=loop).start()
return stopped.set
现在一切似乎都运行良好。现在它运行一小时不停。 但是,尽管在我出现奇怪行为之前它并没有因为我遇到的错误而崩溃。在运行 5 分钟内,断开时间比开始时多一秒。 正如@ErikR 所说,我开始问自己 snap7-python 是否有问题,我每次都在做一些没有连接/断开连接的测试。
【问题讨论】:
-
您不需要多个线程来定期调用函数而不会阻塞主线程。这是code example that uses a single thread
标签: python multithreading timer raspbian