2012-08-06 32 views
0

我有用于运行一段代码,每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() 

莫名其妙的行为就好像它忽略线程,并给出了一个递归限制错误

回答

10

试试这个:

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

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

第二个版本“忽略线程”的原因是您调用Timer调用的参数内部的方法,所以它在定时器启动之前运行(并尝试再次调用自身)。这就是为什么线程函数需要单独传递函数和参数(所以它可以在准备好时调用函数本身)。

顺便说一句,你拼写“连续”错误。

+0

是的这个作品,谢谢 – adam 2012-08-06 05:28:56