#!/usr/bin/env python
# -*- coding: utf-8 -*-
import threading
import time
from Queue import Queue
class _timerThread(threading.Thread):
def __init__(self, t_name,queue,cond):
threading.Thread.__init__(self, name=t_name)
self.threadtimes = []
self.threadFunc = {}
self.lasttimes = {}
self.queue = queue
def setNewTimer(self,newobj):
if newobj.func == None:
self.threadtimes.remove(newobj.secendtime)
self.threadFunc[str(newobj.secendtime)] = None
self.lasttimes[str(newobj.secendtime)] = None
else:
if newobj.secendtime in self.threadtimes:
self.threadFunc[str(newobj.secendtime)] = newobj.func
self.lasttimes[str(newobj.secendtime)] = int(time.time())
else:
self.threadtimes.append(newobj.secendtime)
self.threadFunc[str(newobj.secendtime)] = newobj.func
self.lasttimes[str(newobj.secendtime)] = int(time.time())
def run(self):
while(True):
if not self.queue.empty():
objtmp = self.queue.get()
self.setNewTimer(objtmp)
timetmp = int(time.time())
for tx in self.threadtimes:
if timetmp - self.lasttimes[str(tx)] >= tx:
self.lasttimes[str(tx)] = timetmp
self.threadFunc[str(tx)](timetmp)
self.condition.release()
class _timerObj():
def __init__(self,secendt,funct):
self.secendtime = secendt
self.func = funct
class pytimer():
def __init__(self):
self.queue = Queue()
self.cond = threading.Condition()
self.t_thread = _timerThread(str(int(time.time())),self.queue, self.cond)
self._timers = []
self._initTimer()
def _initTimer(self):
self.t_thread.setDaemon(True)
self.t_thread.start()
def getTimers(self):
return self._timers
def setTimer(self,secendTime,Func):
objtmp = _timerObj(secendTime,Func)
self._timers.append(secendTime)
self.queue.put(objtmp)
def removeTimer(self,secendTime):
objtmp = _timerObj(secendTime,None)
self._timers.remove(secendTime)
self.queue.put(objtmp)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pytimer
def timerCallBack(timex):
print timex
def main():
timerx = pytimer.pytimer()
timerx.setTimer(2, timerCallBack)
while(True):
pass
if __name__ == '__main__':
main()
1446334639
1446334641
1446334643
1446334645
1446334647
1446334649
1446334651
1446334653
...
运行结果与预期想要的结果相同。每两秒调用了一次定时器返回函数。