Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/252.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Timer python类的内部计时器_Timer_Python Multithreading - Fatal编程技术网

Timer python类的内部计时器

Timer python类的内部计时器,timer,python-multithreading,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 )

我正在编写一些具有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()

奇怪的是,如果我删除change函数的参数,然后在不传递args=self的情况下初始化计时器,它就会工作。我为change函数传递参数的原因是,如果状态已更新,我希望重新启动计时器。关于如何做/解决这个问题有什么想法吗?谢谢

所以我认为在XXX类中移动change函数更容易。这样,就不需要传递args=。。。到计时器

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