1
私はステータス属性を持ついくつかのPythonクラスを書いています。オブジェクトXのステータスが30秒間で変化しない場合、つまり「タイムアウト」メッセージのようなものを受信したい場合は、通知を受けたいと思います。私はクラスThreadingのTimerサブクラスを使用しようとしました。しかし、私はエラーPythonクラスの内部タイマー
import threading
import datetime
import time
def change(ob):
print "TIMED OUT"
ob.timer = threading.Timer(30, change, args = ob)
ob.timer.start()
return
class XXX(object):
def __init__(self):
self.status = 0
self.last_change = datetime.datetime.utcnow()
self.timer = threading.Timer(30, change)
self.timer.start()
def set(self, new_status):
D = datetime.timedelta(0, 30)
if (datetime.datetime.utcnow() < self.last_change + D):
self.timer.cancel()
self.last_change = datetime.datetime.utcnow()
self.status = new_status
self.timer = threading.Timer(30, change, args = self)
self.timer.start()
print "New status: ", new_status
def main():
myx = XXX()
x = 0
while (x < 120):
x += 1
print "Second ", x
if (x == 10):
myx.set(20)
elif (x == 40):
myx.set(44)
elif (x == 101):
myx.set(2)
time.sleep(1)
if __name__=='__main__':
main()
を取得しかし、私は、次の例外が発生し得るwhileループで第二40時:
Exception in thread Thread-7:
Traceback (most recent call last):
File "C:\Users\alexa\Anaconda2\lib\threading.py", line 801, in
__bootstrap_inner
self.run()
File "C:\Users\alexa\Anaconda2\lib\threading.py", line 1073, in run
self.function(*self.args, **self.kwargs)
TypeError: change() argument after * must be an iterable, not XXX
奇妙なことは、私はその後、変更関数の引数を削除した場合ということですargs = selfを渡さずにタイマーを初期化すると動作します。私が変更機能の引数を渡したのは、ステータスが更新された場合にタイマーを再起動したかったからです。これを行う/修正する方法に関する考えはありますか?ありがとう!