类方法的python线程计时器

ada*_*dam 2 python multithreading timer

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

def hello():
    print "hello, world"
    t = threading.Timer(30.0, hello)
    t.start()
Run Code Online (Sandbox Code Playgroud)

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

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

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

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)
Run Code Online (Sandbox Code Playgroud)

我也试过了

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

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

Bre*_*arn 12

试试这个:

t = threading.Timer(30.0, self.continousUpdate, [contractId],{} )
Run Code Online (Sandbox Code Playgroud)

当您阅读时self.continuousUpdate,该方法已绑定到该对象,即使您尚未调用它.你不需要self再次通过.

第二个版本"忽略线程"的原因是你在调用的参数内调用方法Timer,因此它在Timer启动之前运行(并尝试再次调用自身).这就是为什么线程函数可以单独传递函数及其参数(因此它可以在函数准备就绪时调用它).

顺便说一句,你拼写"连续"错误.