如何用python实现一个多线程定时器

本文介绍了一个简单的Python定时器类的实现方法,通过多线程技术实现了周期性地调用指定函数的功能,并提供了一个示例程序验证了其有效性。
因为自已要写一个和时间有关的方法,每过几秒钟之后要运行一个函数,但在主线程里写一个死循环来作定时器总是觉得不好。正好今天学习了一下python的多线程,可以拿来练手。写了下边的python定时器类,使用这个类你可以在你的代码中加入一个定时器。
代码如下(pytimer.py):

#!/usr/bin/env python

# -*- coding: utf-8 -*-

import threading  

import time

from Queue import Queue  


class _timerThread(threading.Thread):  

    def __init__(self, t_name,queue,cond):  

        threading.Thread.__init__(self, name=t_name) 

        self.threadtimes = []

        self.threadFunc = {}

        self.lasttimes = {}

        self.queue = queue

    def setNewTimer(self,newobj):

        if newobj.func == None:

            self.threadtimes.remove(newobj.secendtime)

            self.threadFunc[str(newobj.secendtime)] = None

            self.lasttimes[str(newobj.secendtime)] = None

        else:

            if newobj.secendtime in self.threadtimes:

                self.threadFunc[str(newobj.secendtime)] = newobj.func

                self.lasttimes[str(newobj.secendtime)] = int(time.time())

            else:

                self.threadtimes.append(newobj.secendtime)

                self.threadFunc[str(newobj.secendtime)] = newobj.func

                self.lasttimes[str(newobj.secendtime)] = int(time.time())

    def run(self):

        while(True):

            if not self.queue.empty():

                objtmp = self.queue.get()

                self.setNewTimer(objtmp)

            timetmp = int(time.time())

            for tx in self.threadtimes:

                if timetmp - self.lasttimes[str(tx)] >= tx:

                    self.lasttimes[str(tx)] = timetmp

                    self.threadFunc[str(tx)](timetmp)

        self.condition.release()

        

class _timerObj():

    def __init__(self,secendt,funct):

        self.secendtime = secendt

        self.func = funct

    

class pytimer():

    def __init__(self):

        self.queue = Queue()   

        self.cond = threading.Condition()

        self.t_thread = _timerThread(str(int(time.time())),self.queue, self.cond) 

        self._timers = []

        self._initTimer()

    def _initTimer(self):

        self.t_thread.setDaemon(True)

        self.t_thread.start()

    def getTimers(self):

        return self._timers

    def setTimer(self,secendTime,Func):

        objtmp = _timerObj(secendTime,Func)

        self._timers.append(secendTime)

        self.queue.put(objtmp)

    def removeTimer(self,secendTime):

        objtmp = _timerObj(secendTime,None)

        self._timers.remove(secendTime)

        self.queue.put(objtmp)


功能测试(test.py):

#!/usr/bin/env python

# -*- coding: utf-8 -*-

import pytimer


def timerCallBack(timex):

    print timex


def main():  

    timerx = pytimer.pytimer()

    timerx.setTimer(2, timerCallBack)

    while(True):

        pass

if __name__ == '__main__':  

    main()


运行测试程序后输出结果:

1446334639

1446334641

1446334643

1446334645

1446334647

1446334649

1446334651

1446334653

...

运行结果与预期想要的结果相同。每两秒调用了一次定时器返回函数。

源码获取地址: https://github.com/fengmm521/pytimer/tree/master
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值