博客
关于我
python多个定时器_python单线程实现多个定时器示例
阅读量:796 次
发布时间: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基础之--面相对象--OOP基本特性
    查看>>
    python基础之--迭代器和生成器及异常处理
    查看>>
    python基础之--包和模块
    查看>>
    python基础之---面向对象--属性和方法
    查看>>
    python基础之---运算符
    查看>>
    python基础之---语句
    查看>>
    python基础之---正则表达式
    查看>>
    python基础之---函数式编程
    查看>>
    python基础之---函数
    查看>>
    Python基础之(一)基本数据类型
    查看>>
    Python基础【os】
    查看>>
    Python基础——面向对象
    查看>>
    Python基础——线程锁
    查看>>
    python基础——线程与进程
    查看>>
    Python基础——构造方法和特殊成员方法
    查看>>
    Python基础——多线程值从Thread类继承
    查看>>
    Python基础——多线程之信号量
    查看>>
    Python基础——_thread多线程
    查看>>
    Python基础——Thread类与线程对象
    查看>>
    Python基础——Thread创建管理多线程
    查看>>