【问题标题】:Python periodic timer generate too many threadPython 周期定时器产生太多线程
【发布时间】: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 是否有问题,我每次都在做一些没有连接/断开连接的测试。

【问题讨论】:

标签: python multithreading timer raspbian


【解决方案1】:

这是一种似乎不会泄漏任何线程的方法。注意 - 在周期性操作完成之前,这不会创建新的计时器。

#!/usr/bin/python

import time, threading

class MyPeriodic:
  def __init__(self):
    self.count = 0

  def start(self):
    self._timer = threading.Timer(1, self._run)
    self._timer.start()

  def stop(self):
    if self._timer:
      self._timer.cancel()
      self._timer = None

  def _run(self):
    self.stop()
    self.count += 1
    print "iteration:", self.count, "active:", threading.active_count(), "time:", time.ctime()
    self.start()

【讨论】:

  • 感谢您的方法,但我得到了相同的结果:'迭代:241 活动:2 时间:2016 年 5 月 13 日星期五 16:01:40 FromEmit 1463155300.82 线程 Thread-241 中的异常:回溯(最近最后调用):文件“/usr/lib/python2.7/threading.py”,第 810 行,在 __bootstrap_inner'
  • 那么snap7库或者你使用的方式有问题。也许 snap7 库正在耗尽系统线程。发布显示问题的最小示例。
猜你喜欢
  • 2020-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多