user1566114
user1566114

Reputation: 145

internal timer of python class

I am writing some Python class which has a status attribute. I would like to be notified if the status of an object X does not change in 30 seconds i.e. I want to receive something like a "Timeout" message. I tried to use the Timer subclass of the class Threading. But I get an error

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()

But at Second 40 in the while loop I get the following exception raised:

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

The weird thing is that if I remove the arguments of the change function and then initialize the timer without passing args = self, it works. The reason why I was passing arguments for the change function is that I wanted to restart the timer if the status was updated. Any thoughts on how to do/fix this? Thanks!

Upvotes: 1

Views: 893

Answers (1)

user1566114
user1566114

Reputation: 145

so I figured that it's just easier to move the change function inside the XXX class. This way, one does not need to pass args = ... to the timer.

Upvotes: 1

Related Questions