[Python-checkins] CVS: python/dist/src/Lib threading.py,1.17,1.18
Martin v. L?wis
loewis@users.sourceforge.net
Wed, 05 Sep 2001 06:44:56 -0700
Update of /cvsroot/python/python/dist/src/Lib
In directory usw-pr-cvs1:/tmp/cvs-serv28325/Lib
Modified Files:
threading.py
Log Message:
Patch #428326: New class threading.Timer.
Index: threading.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/threading.py,v
retrieving revision 1.17
retrieving revision 1.18
diff -C2 -d -r1.17 -r1.18
*** threading.py 2001/08/20 20:27:58 1.17
--- threading.py 2001/09/05 13:44:54 1.18
***************
*** 332,336 ****
self.__cond.release()
-
# Helper to generate new thread names
_counter = 0
--- 332,335 ----
***************
*** 484,487 ****
--- 483,516 ----
self.__daemonic = daemonic
+ # The timer class was contributed by Itamar Shtull-Trauring
+
+ def Timer(*args, **kwargs):
+ return _Timer(*args, **kwargs)
+
+ class _Timer(Thread):
+ """Call a function after a specified number of seconds:
+
+ t = Timer(30.0, f, args=[], kwargs={})
+ t.start()
+ t.cancel() # stop the timer's action if it's still waiting
+ """
+
+ def __init__(self, interval, function, args=[], kwargs={}):
+ Thread.__init__(self)
+ self.interval = interval
+ self.function = function
+ self.args = args
+ self.kwargs = kwargs
+ self.finished = Event()
+
+ def cancel(self):
+ """Stop the timer if it hasn't finished yet"""
+ self.finished.set()
+
+ def run(self):
+ self.finished.wait(self.interval)
+ if not self.finished.isSet():
+ self.function(*self.args, **self.kwargs)
+ self.finished.set()
# Special thread class to represent the main thread