python class 的内部计时器

internal timer of python class

我正在写一些具有状态属性的 Python class。如果对象 X 的状态在 30 秒内没有改变,我想收到通知,即我想收到类似 "Timeout" 的消息。我尝试使用 class 线程的 Timer subclass。但是我得到一个错误

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 的情况下初始化计时器,它就可以工作。我为 change 函数传递参数的原因是我想在状态更新时重新启动计时器。关于如何 do/fix 有什么想法吗?谢谢!

所以我认为将更改功能移到 XXX class 中会更容易。这样,就不需要将 args = ... 传递给计时器。