类方法上的python线程计时器
我有一个代码块,用于每30秒运行一段代码类方法上的python线程计时器,python,multithreading,timer,Python,Multithreading,Timer,我有一个代码块,用于每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, s
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
时,该方法已绑定到该对象,即使您尚未调用它。您无需再次通过self
第二个版本“忽略线程”的原因是您在计时器调用的参数中调用了该方法,因此它在计时器启动之前运行(并尝试再次调用自身)。这就是线程函数让您分别传递函数及其参数的原因(这样它就可以在函数准备就绪时调用函数本身)
顺便说一句,您将“continuous”拼写错误。只需删除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()