python类

时间:2017-10-30 09:55:02

标签: timer python-multithreading

我正在编写一些具有status属性的Python类。如果对象X的状态在30秒内没有改变,我希望收到通知,即我希望收到类似“超时”消息的内容。我试图使用类Threading的Timer子类。但是我收到了错误

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的情况下初始化计时器,它就可以工作。我为更改函数传递参数的原因是我想在状态更新时重新启动计时器。有关如何做/解决此问题的任何想法?谢谢!

1 个答案:

答案 0 :(得分:1)

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