codingpp
2014-05-20 18:54:15 +08:00
import time
import threading
from heapq import heappush, heappop, heapify
class TaskCall(object):
def __init__(self, runtime, func, args):
self.runtime = runtime
self.func = func
self.args = args
def __lt__(self, other):
return self.runtime < other.runtime
def __le__(self, other):
return self.runtime <= other.runtime
def __gt__(self, other):
return self.runtime > other.runtime
def __ge__(self, other):
return self.runtime >= other.runtime
class Timer(object):
def __init__(self):
self.squeue = []
self.newtasks = []
def add(self, second, func, args = ()):
runtime = time.time() + second
task = TaskCall(runtime, func, args)
self.newtasks.append(task)
def loop(self):
while(True):
while len(self.newtasks) != 0:
heappush(self.squeue, self.newtasks.pop())
while self.squeue and (self.squeue[0].runtime <= time.time()):
task = heappop(self.squeue)
apply(task.func, task.args)
time.sleep(0.1)
timer = Timer()
if __name__ == '__main__':
def printsome(i):
print i
def exitprocess(i):
exit()
timer.add(2, printsome, (2,))
timer.add(5, printsome, (5,))
timer.add(5, printsome, (5,))
timer.add(5, printsome, (5,))
timer.add(5, printsome, (5,))
timer.add(1, printsome, (1,))
timer.add(7, exitprocess, (1,))
timer.loop()
之前写过的一段代码,应该很适合这种场景
堆排序