如何用python实现一个多线程定时器
来源:互联网 发布:linux halt命令 编辑:程序博客网 时间:2024/06/05 09:33
#!/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)
#!/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
...
运行结果与预期想要的结果相同。每两秒调用了一次定时器返回函数。
- 如何用python实现一个多线程定时器
- 看我如何用 Python 实现一个轻量型数据库
- 如何用Python写一个贪吃蛇
- 如何用Python实现八大排序算法
- 如何用Python实现八大排序算法
- 如何用Python实现目录遍历
- 如何用 Python 实现 Web 抓取?
- 如何用 Python 实现 Web 抓取?
- 如何用C++实现一个LRU Cache
- 如何用两个栈实现一个队列
- 如何用两个栈实现一个队列
- 如何用两个栈实现一个队列
- 如何用C++实现一个LRU Cache
- 如何用C++实现一个LRU Cache
- 如何用两个栈实现一个队列
- 如何用C++实现一个LRU Cache
- 如何用一个栈实现队列?
- python中多线程如何用Ctrl+C终止
- Clickteam Fusion 2.5 iOS上使用触摸手柄
- 在游戏开发中的使用icade手柄
- hive学习记录
- 比特币开发指南
- python中的多线程
- 如何用python实现一个多线程定时器
- cocos2d-x中lua与C++,C语言互相调用
- python写入mysql中文乱码问题
- 使用python多线程连接mysql数据库
- 在wxPython中使用多线程
- mysql插入数据不成功
- MYSQL获取自增ID的四种方法(转)
- python解决address already in use
- MySql数据库编程