Here I just want to keep it simple. If you want to execute a function every n second, this function should be competent. However, please note that the task is actually executed in another thread.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | import threading
from time import sleep
def intervalExecute(interval, func, *args, **argd):
''' @param interval: execute func(*args, **argd) each interval
@return: a callable object to enable you terminate the timer.
'''
cancelled = threading.Event()
def threadProc(*args, **argd):
while True:
cancelled.wait(interval)
if cancelled.isSet():
break
func(*args, **argd) #: could be a lenthy operation
th = threading.Thread(target=threadProc, args=args, kwargs=argd)
th.start()
def close(block=True, timeout=3):
''' @param block: if True, block the caller until the thread
is closed or time out
@param timout: if blocked, timeout is used
@return: if block, True -> close successfully; False -> timeout
if non block, always return False
'''
if not block:
cancelled.set()
return False
else:
cancelled.set()
th.join(timeout)
isClosed = not th.isAlive()
return isClosed
return close
if __name__=='__main__':
# sample usage is as follow....
def testFunc(identifier, txt=''):
print 'test func entered'
sleep(2)
print identifier, txt
cancellObj = intervalExecute(2.0, testFunc, 1, 'haha')
help(cancellObj)
sleep(5.2)
print cancellObj() #: cancel the intervalExecute timer.
print 'after calling close'
|