本文共 3505 字,大约阅读时间需要 11 分钟。
以下是实现单线程环境下多个定时任务的Python代码示例:
#!/usr/bin/env pythonfrom heapq import *from threading import Timerimport threadingimport uuidimport timeimport datetimeimport sysimport mathglobal TimerStampglobal TimerTimesclass CancelFail(Exception): passclass 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 = kwargsclass NewTimer(object): def __init__(self, resolution=1000): global TimerStamp TimerStamp = int(time.time() * 1000) self.nofire = sys.maxint self.firestamp = self.nofire + TimerStamp self.resolution = resolution self.lock = threading.RLock() self.wait = dict() self.ready = dict() self._start() 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) if boxs: if slot.id in boxs: boxs.pop(slot.id) if not boxs: self.ready.pop(slot.fire) def _start(self): current_time = int(time.time() * 1000) self.nofire = current_time self.firestamp = self.nofire + self.resolution self._schedule() def _schedule(self): current_time = int(time.time() * 1000) if self.firestamp <= current_time: self._handleExpired() if self.firestamp <= current_time: self._processReadyTasks() def _handleExpired(self): current_time = int(time.time() * 1000) self.nofire = current_time self.firestamp = self.nofire + self.resolution self._schedule() def _processReadyTasks(self): current_time = int(time.time() * 1000) while self.firestamp <= current_time: if self.ready: firestamp, slots = next(iter(self.ready.items())) if firestamp <= current_time: self._executeTask(firestamp, slots) self._delFromReadyList(slots[0]) self._handleExpired() else: break def _executeTask(self, firestamp, slot): try: slot.function(**slot.kwargs) except CancelFail: pass def set_timeout(self, milliseconds=1000, callback=None, *args, **kwargs): slot = Slot(period=0, interval=1, function=callback, args=args, kwargs=kwargs) self._schedule() return slot def cancel(self, slot): slot.fire = 0 if slot.id in self.wait: self.wait[slot.id].cancel() self._delFromReadyList(slot) 该代码实现了在单线程环境下管理多个定时任务的功能。通过使用优先队列(heapq)和主线程处理定时任务的方式,确保了定时任务能够高效执行。
heapq模块来管理定时任务的执行顺序,确保任务按时间优先级执行。threading.RLock确保在多线程环境下数据访问的同步性。set_timeout方法创建新的定时任务。cancel方法停止指定的定时任务。Slot对象执行,支持通过function参数指定具体的执行逻辑。ready和wait字典分别管理待执行和已完成的任务,确保任务高效执行。通过上述实现,可以在单线程环境下高效管理和执行多个定时任务。
转载地址:http://uxofk.baihongyu.com/