服务器定时器的管理优化(思路借鉴)
from common import Timer
from util import TimeUtil
from base.Defines import *
class TimerObj(object):
"""封装一个定时器对象"""
def __init__(self, start_time, interval, callback):
"""
:param start_time:定时器开始时间
:param interval:定时器间隔,如果只执行一次,填0
:param callback:触发定时器时执行的函数
:return:
"""
super(TimerObj, self).__init__()
self.start = start_time
self.interval = interval
self.callback = callback
def getEndTime(self):
if self.interval <= 0:
return self.start
return None
def getNextTime(self):
now_time = int(TimeUtil.now_time())
if now_time < self.start:
return self.start
else:
if self.getEndTime() is not None:
return None
num = 0
while self.start + num <= now_time:
num += self.interval
return self.start + num
class TimerManager(object):
"""管理所有的定时器"""
def __init__(self):
super(TimerManager, self).__init__()
self.timer_list = []
self.timer = None
def addTimerObj(self, obj):
self.timer_list.append(obj)
self.stopTimer()
self.startTimer()
def removeTimeObj(self, type):
pass
def getMinNextTimer(self):
min_next = INT_MAX
result = []
self.timer_list = filter(lambda x:x.getNextTime() is not None, self.timer_list)
for obj in self.timer_list:
next = obj.getNextTime()
if next < min_next:
min_next = next
result = []
result.append(obj)
elif next == min_next:
result.append(obj)
if min_next == INT_MAX:
return None,None
#print "getMinNextTimer",min_next,int(TimeUtil.now_time())
return min_next, result
def startTimer(self):
timestamp, objlist = self.getMinNextTimer()
if timestamp is None:
return
self.stopTimer()
delay = int(timestamp) - int(TimeUtil.now_time())
if delay == 0:
delay = 1
self.timer = Timer.addTimer(delay, lambda :self.callTimer(objlist))
def callTimer(self, objlist):
#print "callTimer",int(TimeUtil.now_time())
self.startTimer()
for obj in objlist:
obj.callback()
def stopTimer(self):
if self.timer is not None:
self.timer.cancel()
self.timer = None