【问题标题】:python threading timer on a class method类方法上的python线程计时器
【发布时间】:2012-08-06 05:21:25
【问题描述】:

我有一个代码块,用于每 30 秒运行一段代码

def hello():
    print "hello, world"
    t = threading.Timer(30.0, hello)
    t.start()

下面是一个类的方法,我真的很想每 30 秒运行一次,但我遇到了问题。

def continousUpdate(self, contractId):    
    print 'hello, world new'
    t = threading.Timer(30.0, self.continousUpdate, [self, contractId],{} )
    t.start()

当我运行它时,我得到以下错误

pydev debugger: starting
hello, world new
Exception in thread Thread-4:
Traceback (most recent call last):
  File "C:\Python27\lib\threading.py", line 552, in __bootstrap_inner
   self.run()
  File "C:\Python27\lib\threading.py", line 756, in run
   self.function(*self.args, **self.kwargs)
TypeError: continousUpdate() takes exactly 2 arguments (3 given)

我也试过

def continousUpdate(self, contractId):    
    print 'hello, world new'
    t = threading.Timer(30.0, self.continousUpdate(contractId))
    t.start()

它以某种方式表现得好像它忽略了线程,并给出了递归限制错误

【问题讨论】:

    标签: python multithreading timer


    【解决方案1】:

    试试这个:

    t = threading.Timer(30.0, self.continousUpdate, [contractId],{} )
    

    当您阅读self.continuousUpdate 时,该方法已经绑定到该对象,即使您还没有调用它。您无需再次传递self

    第二个版本“忽略线程”的原因是您在 Timer 调用的参数中调用该方法,因此它在 Timer 启动之前运行(并尝试再次调用自身)。这就是为什么线程函数让你分别传递函数及其参数(因此它可以在准备好时调用函数本身)。

    顺便说一句,你拼错了“continuous”。

    【讨论】:

      【解决方案2】:

      只需删除self 参数。 这是一个完整的工作解决方案:

      import threading
      class DataCollect():
          def __init__(self):
              pass
      
          def hello(self):
              print("hello, world")
              t = threading.Timer(5.0, self.hello)
              t.start()
              
      dataCollect = DataCollect() 
      dataCollect.hello()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-03-05
        • 1970-01-01
        • 1970-01-01
        • 2015-01-13
        • 2018-06-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多