单线程实现多个定时器
NewTimer.py
代码如下:
#!/usr/bin/env python
from heapq import *
from threading import Timer
import threading
import uuid
import time
import datetime
import sys
import math
global TimerStamp
global TimerTimes
class CancelFail(Exception):
pass
class Slot(object):
def __init__(self, period=0, interval=1, function=None, args=[], kwargs={}):
self.period = period
self.pc = 0
self.interval = interval
self.fire = 0
self.id = uuid.uuid1()
self.function = function
self.args = args
self.kwargs = kwargs
#system resolution millisecond
class NewTimer(object):
#set enough time make thread sleep, when NewTimer empty set enoug time, too
#make sure sum of your timer call back function execute time shorter than resolution
#todo use a worker thread to operate timer call back function
def __init__(self, resolution=1000):
global TimerStamp
TimerStamp = int(time.time() * 1000)
self.nofire = sys.maxint #next fire time interval
self.firestamp = self.nofire + TimerStamp
self.resolution = resolution# 1s
self.lock = threading.RLock()
self.wait = dict()
self.ready = dict()
self._start()
""" private operate ready list """
def _addToReadyList(self, slot, firestamp):
box = dict( [ (slot.id, slot)])
if not self.ready.has_key( firestamp ):
self.ready.update( [(firestamp, box)] )
else:
boxs = self.ready.get(firestamp)
boxs.update( box )
def _delFromReadyList(self, slot):
boxs = self.ready.get(slot.fire)
try:
box = boxs.pop(slot.id)
新闻热点
疑难解答