我有一个代码块,用于每 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()
它以某种方式表现得好像它忽略了线程,并给出递归限制错误
最佳答案
试试这个:
t = threading.Timer(30.0, self.continousUpdate, [contractId],{} )
当您阅读 self.continuousUpdate
时,该方法已经绑定(bind)到该对象,即使您尚未调用它也是如此。您不需要再次传递 self
。
第二个版本“忽略线程”的原因是您在 Timer
调用的参数中调用该方法,因此它在 Timer 获取之前运行(并尝试再次调用自身)开始了。这就是线程函数让您分别传递函数及其参数的原因(因此它可以在准备就绪时调用函数本身)。
顺便说一下,你拼错了“continuous”。
关于类方法上的python线程计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11822879/