python单线程实现多个定时器示例

单线程实现多个定时器

NewTimer.py


代码如下:

#!/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

#system resolution millisecond        
class NewTimer(object):

#set enough time make thread sleep, when NewTimer empty set enoug time, too
    #make sure sum of your timer call back function execute time shorter than resolution
    #todo use a worker thread to operate timer call back function
    def __init__(self, resolution=1000):
        global TimerStamp
        TimerStamp = int(time.time() * 1000)

self.nofire = sys.maxint #next fire time interval
        self.firestamp = self.nofire + TimerStamp
        self.resolution = resolution# 1s

self.lock = threading.RLock()

self.wait = dict()
        self.ready = dict()

self._start()

""" private operate ready list """
    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)
        try:
            box = boxs.pop(slot.id)
            if not boxs:
                self.ready.pop(slot.fire)
        except (AttributeError, KeyError):
            raise CancelFail

""" inside """
    def _start(self):
        global TimerStamp

try:
            self.firestamp = sorted( self.ready.keys() )[0]
            stamp = float((TimerStamp + self.firestamp - int(time.time()*1000)))/1000
        except IndexError:
            self.firestamp = self.nofire
            stamp = self.nofire

try:
            self.timer.cancel()
        except AttributeError:
            pass

self.timer = Timer( stamp, self.hander)
        self.timer.start()

def hander(self, *args, **kwargs):
        """ find time arrive slot, do it function """

self.lock.acquire()

try:
            boxs = self.ready.pop( self.firestamp )
            slots = boxs.values()
        except KeyError:
            slots = []

for slot in slots:
            if slot.period:
                slot.pc += 1
                if slot.pc != slot.period:
                    slot.fire = slot.interval + slot.fire
                    self._addToReadyList(slot, slot.fire)
            elif slot.period == -1:
                slot.fire = slot.interval + slot.fire
                self._addToReadyList(slot, slot.fire)

""" """
        self._start()
        self.lock.release()

for slot in slots:
            try:
                slot.function(slot.args, slot.kwargs)
            except Exception:
                print "slot id %s, timer function fail" % slot.id

""" operate new timer manager itself """
    def stop(self):
        self.timer.cancel()

""" new timer manager """
    def add(self, period=0, interval=1, function=None, args=[], kwargs={}):
        """
        period: one time = 0, times = >0, always = -1
        interval: timer fire relative TimerReference
        function: when timer fire, call back function
        args,kwargs: callback function args
        """
        interval = int(interval) * self.resolution#seconds
        if interval < self.resolution:
            interval = self.resolution

slot = Slot( period, interval, function, *args, **kwargs )
        box = dict([(slot.id, slot)])
        self.wait.update(box)

return slot

def remove(self, slot):
        if isinstance(slot, Slot):
            self.cancel(slot)

try:
                self.wait.pop(slot.id)
            except KeyError:
                print "wait dict not has the cancel timer"

""" timer api """
    def reset(self, slot):
        if isinstance(slot, Slot):
            self.cancel(slot)
            slot.pc = 0
            self.start(slot)

def start(self, slot):

def NewTimerStamp(timebase, resolution):
            nowoffset = int(time.time() * 1000) - timebase
            if nowoffset % resolution < resolution / 10:
                currentstamp =  nowoffset / resolution
            else:
                currentstamp = (nowoffset + resolution - 1) / resolution

return currentstamp * 1000

global TimerStamp
        if isinstance(slot, Slot):
            firestamp = slot.interval + NewTimerStamp(TimerStamp, self.resolution)
            slot.fire = firestamp

self.lock.acquire()
            self._addToReadyList(slot, firestamp)
            if self.firestamp > slot.fire:
                self._start()
            self.lock.release()

def cancel(self, slot):
        if isinstance(slot, Slot):
            try: 
                self.lock.acquire()
                self._delFromReadyList(slot)
                self._start()
                self.lock.release()
            except CancelFail:
                self.lock.release()

def hello( *args, **kargs):
    print args[0], datetime.datetime.now()

if __name__ == "__main__":

print "start test timer", datetime.datetime.now()

nt = NewTimer(500)
    t0 = nt.add( -1, 5, hello, [0])
    t1 = nt.add( 4, 7, hello, [1])
    t2 = nt.add( 1, 3, hello, [2])#
    t3 = nt.add( 1, 4, hello, [3])#
    t4 = nt.add( 4, 5, hello, [4])
    t5 = nt.add( 12, 5, hello, [5])#
    t6 = nt.add( 9, 7, hello, [6])
    t7 = nt.add( 1, 8, hello, [7])#
    t8 = nt.add( 40, 1, hello, [8])

nt.start( t0 )
    nt.start( t1 )
    nt.start( t2 )#
    nt.start( t3 )#
    nt.start( t4 )
    nt.start( t5 )#
    nt.start( t6 )
    nt.start( t7 )#
    nt.start( t8 )

nt.cancel(t2)
    nt.cancel(t3)

nt.remove(t5)
    nt.remove(t3)

time.sleep(3)

nt.start(t2)
    nt.cancel(t8)

time.sleep(300)
    nt.stop()

print "finish test timer", datetime.datetime.now()

(0)

相关推荐

  • python实现socket客户端和服务端简单示例

    复制代码 代码如下: import socket#socket通信客户端def client():    mysocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)    mysocket.connect(('127.0.0.1',8000))    mysocket.send('hello')    while 1:        data=mysocket.recv(1024)        if data:           pri

  • python实现单线程多任务非阻塞TCP服务端

    本文实例为大家分享了python实现单线程多任务非阻塞TCP服务端的具体代码,供大家参考,具体内容如下 # coding:utf-8 from socket import * # 1.创建服务器socket sock = socket(AF_INET, SOCK_STREAM) # 2.绑定主机和端口 addr = ('', 7788) # sock.bind(addr) # 3. 设置最大监听数目,并发 sock.listen(10) # 4. 设置成非阻塞 sock.setblocking(

  • Python 爬虫学习笔记之单线程爬虫

    介绍 本篇文章主要介绍如何爬取麦子学院的课程信息(本爬虫仍是单线程爬虫),在开始介绍之前,先来看看结果示意图 怎么样,是不是已经跃跃欲试了?首先让我们打开麦子学院的网址,然后找到麦子学院的全部课程信息,像下面这样 这个时候进行翻页,观看网址的变化,首先,第一页的网址是 http://www.maiziedu.com/course/list/, 第二页变成了 http://www.maiziedu.com/course/list/all-all/0-2/, 第三页变成了 http://www.ma

  • python单线程实现多个定时器示例

    单线程实现多个定时器 NewTimer.py 复制代码 代码如下: #!/usr/bin/env python from heapq import *from threading import Timerimport threadingimport uuidimport timeimport datetimeimport sysimport math global TimerStampglobal TimerTimes class CancelFail(Exception):    pass c

  • python单线程文件传输的实例(C/S)

    客户端代码: #-*-encoding:utf-8-*- import socket import os import sys import math import time def progressbar(cur, total): percent = '{:.2%}'.format(float(cur) / float(total)) sys.stdout.write('\r') sys.stdout.write("[%-50s] %s" % ( '=' * int(math.flo

  • python线程池 ThreadPoolExecutor 的用法示例

    前言 从Python3.2开始,标准库为我们提供了 concurrent.futures 模块,它提供了 ThreadPoolExecutor (线程池)和ProcessPoolExecutor (进程池)两个类. 相比 threading 等模块,该模块通过 submit 返回的是一个 future 对象,它是一个未来可期的对象,通过它可以获悉线程的状态主线程(或进程)中可以获取某一个线程(进程)执行的状态或者某一个任务执行的状态及返回值: 主线程可以获取某一个线程(或者任务的)的状态,以及返

  • python 多线程实现多任务的方法示例

    目录 1 多线程实现多任务 1.1 什么是线程? 1.2 一个程序实现多任务的方法 1.3 多线程的创建方式 1.3.1 创建threading.Thread对象 1.3.2 继承threading.Thread,并重写run 1.4 线程何时开启,何时结束 1.5 线程的 join() 方法 1.6 多线程共享全局变量出现的问题 1.7 互斥锁可以弥补部分线程安全问题.(互斥锁和GIL锁是不一样的东西!) 1.8 线程池ThreadPoolExecutor 1.8.1 创建线程池 1.8.2 

  • Python实现定时监测网站运行状态的示例代码

    先说一下为啥会写这段代码,大家在浏览网页的时候都会看到友情链接,友情链接里面的链接地址,如果不能正常的,那么在SEO方面会有影响,如何及时的发现无效或者错误的链接并及时对其进行下线处理,这是一个至关重要的问题. 通过定时的监测网站的状态,通常监测地址为网站的域名,如果链接的状态码不是200,那么,就将对其进行下线处理,在特定时间后对其进行二次探测状态,如果符合将其上线,以前使用的创宇云的监控,但是功能比较单一,无法满足需求,近期使用Python来实现这一功能,后期将编写监控模块,并进行代码开源或

  • python编程羊车门问题代码示例

    问题: 有3扇关闭的门,一扇门后面停着汽车,其余门后是山羊,只有主持人知道每扇门后面是什么.参赛者可以选择一扇门,在开启它之前,主持人会开启另外一扇门,露出门后的山羊,然后允许参赛者更换自己的选择. 请问: 1.按照你的第一感觉回答,你觉得不换选择能有更高的几率获得汽车,还是换选择能有更高的几率获得汽车?或几率没有发生变化? 答:第一感觉换与不换获奖几率没有发生变化. 2.请自己认真分析一下"不换选择能有更高的几率获得汽车,还是换选择能有更高的几率获得汽车?或几率没有发生变化?" 写出

  • nodejs中使用HTTP分块响应和定时器示例代码

    在本例中,将要创建一个输出纯文本的HTTP服务器,输出的纯文本每隔一秒会新增100个用换行符分隔的时间戳. require('http').createServer(function(req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); var left = 10; var interval = setInterval(function() { for(var i = 0; i< 100; i++) { res.write

  • python实现简单中文词频统计示例

    本文介绍了python实现简单中文词频统计示例,分享给大家,具体如下: 任务 简单统计一个小说中哪些个汉字出现的频率最高 知识点 1.文件操作 2.字典 3.排序 4.lambda 代码 import codecs import matplotlib.pyplot as plt from pylab import mpl mpl.rcParams['font.sans-serif'] = ['FangSong'] # 指定默认字体 mpl.rcParams['axes.unicode_minus

  • python绘制简单折线图代码示例

    1.画最简单的直线图 代码如下: import numpy as np import matplotlib.pyplot as plt x=[0,1] y=[0,1] plt.figure() plt.plot(x,y) plt.savefig("easyplot.jpg") 结果如下: 代码解释: #x轴,y轴 x=[0,1] y=[0,1] #创建绘图对象 plt.figure() #在当前绘图对象进行绘图(两个参数是x,y轴的数据) plt.plot(x,y) #保存图象 plt

  • python使用logging模块发送邮件代码示例

    logging模块不只是能记录log,还能发送邮件,使用起来非常简单方便 #coding=utf-8 ''''' Created on 2016-3-21 @author: Administrator ''' import logging, logging.handlers class EncodingFormatter(logging.Formatter): def __init__(self, fmt, datefmt=None, encoding=None): logging.Format

随机推荐