类方法上的python线程计时器

标签 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, 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/

相关文章:

ios - 创建多个 NSTimers 倒计时

javascript - Node js 精确定时器

python - 通过 wheezy.template 提供静态文件 css 和 js?

Python约束线性优化

Python argparse 和控制/覆盖退出状态代码

c - 使用线程打印奇数和偶数

c - 为什么我的 GTK+ widget 的 expose 事件在很长时间后会被卡住?它是 GTK+ 错误吗?

android - 如何使用 AsyncTask 从 Url 设置图像?

JavaScript 计时器并不每秒计数

python - readlines 给了我额外的换行符 python2.6.5