将一个方法, 按照设定的时间间隔执行:
主要思路就是
分段:
分段通过将目标函数, 这里是logic(), 用yield分段, 然后coroutine.next()分段执行
时间间隔:
时间间隔, 则是通过一个loop函数, 不断从回调函数堆里获取注册的回调. 判断时间间隔, 并执行, 同时主逻辑中, yield之前, 都要注册一个根本上是coroutine.next()的回调
import heapq import time class P(object): def __init__(self): self.callback_heapq = [] self.coroutine = self.logic() def start(self): self.process() self.loop() def process(self): self.coroutine.next() def loop(self): while True: trigger_time, _cb = heapq.heappop(self.callback_heapq) cur_time = time.time() if trigger_time >= cur_time: _cb() else: heapq.heappush(self.callback_heapq, (trigger_time, _cb)) def addcallback(self, interval, _cb): heapq.heappush(self.callback_heapq, (time.time() + interval, _cb)) def logic(self): print 1 self.addcallback(0.1, self.process) yield print 2 self.addcallback(0.1, self.process) yield print 3 self.addcallback(0.1, self.process) yield if __name__ == '__main__': p = P() p.start()



