博客
关于我
python多个定时器_python单线程实现多个定时器示例
阅读量:797 次
发布时间:2023-03-07

本文共 3505 字,大约阅读时间需要 11 分钟。

单线程环境下实现多个定时任务

代码解析

以下是实现单线程环境下多个定时任务的Python代码示例:

#!/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
class 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参数指定具体的执行逻辑。
  • 优化说明

  • 线程安全:通过锁机制确保在多线程环境下数据操作的安全性。
  • 任务管理:使用readywait字典分别管理待执行和已完成的任务,确保任务高效执行。
  • 时间计算:使用高精度的时间计算,确保定时任务的准确性。
  • 通过上述实现,可以在单线程环境下高效管理和执行多个定时任务。

    转载地址:http://uxofk.baihongyu.com/

    你可能感兴趣的文章
    python基础篇(5):None类型
    查看>>
    python基础篇(4):range语句
    查看>>
    python基础篇(3):print()补偿知识点
    查看>>
    python基础篇(2):字符串扩展知识点
    查看>>
    python基础篇(1):type()
    查看>>
    python基础篇(15):闭包
    查看>>
    python基础篇(14):多态
    查看>>
    python基础篇(13):类型注解
    查看>>
    python基础篇(12):继承
    查看>>
    python基础篇(11):封装
    查看>>
    python基础篇(10):自定义包
    查看>>
    python基础篇(10):类、对象与构造方法
    查看>>
    python系列【仅供参考】:python测试javaSDK总结
    查看>>
    python系列【仅供参考】:python斗地主
    查看>>
    Python基础教程(第2版 修订版) pdf
    查看>>
    python基础实践(四)
    查看>>
    Python基础学习笔记(九)常用数据类型转换函数
    查看>>
    Python基础学习参考(五):字符串和编码
    查看>>
    Python基础学习
    查看>>
    python基础变量之---集合
    查看>>