python 可定制化 定时器

key word:

how to customized a suitable timer in python


因为项目需要,需要使用python 定时器, 在谷歌一番之后,基本获得的信息是调用python 的 threading的timer 定时器, 或者使用schl 模块进行操作。 具体实践方法请自行谷歌之。 

在一番调试之后,发现threading timer 定时器不好控制, 相关资料少,用的不明就里 (个人才疏德浅, 有用的好的同学,欢迎指教。O(∩_∩)O哈哈~)尤其是需要同时启动多个定时器之后,整个程序跑的一团浆糊。 

经过一番地毯式搜索依旧没有找到很好的解决方案之后,始终没有找到一个现成,满意的的快速解决方案。我不得的陷入沉思

根据我搜索的数据分析,所有的定时器都提到了一个词: 线程。 这引发我对自行定制定时器的想法,这个想法很快在我发酵延伸


目标:

我需要的定时器的功能很简单, 有点类似VC 当中的settimer() 

1   能够设定准确的延时时间, 时间误差不超过10 ms 都是可接受的。 

2   在定时timeout 之后,会自动触发用户函数进行响应

3   定时器可设置是否循环操作,比如每隔2 秒自动刷新一次

4   可强制kill 定时器


在明确了自身对 定时器的需求之后,对定时器所要求的基本功能也就明确了

通过自建一个线程类并且开始计时,timeout 之后,自动执行设定函数。

现有的定时器虽然不好搞,缺乏相关资料,但是线程确实非常熟悉的。

请看代码: 

import threading
import time
定时器类

class Pysettimer(threading.Thread):
    '''
    Pysettimer is simulate the C++ settimer ,
    it need  pass funciton pionter into the class , 
    timeout and is_loop could be default , or customized
    '''
    def __init__(self, function, args=None,timeout=1,is_loop=False):
        threading.Thread.__init__(self)
        self.event=threading.Event()
        # inherent the funciton and args
        self.function=function
        self.args=args      # pass a tuple into the class
        self.timeout=timeout
        self.is_loop=is_loop

    def run(self):
        while not self.event.is_set():
            self.event.wait(self.timeout) # wait until the time eclipse

            self.function(self.args)

            if not  self.is_loop:
                self.event.set()

    def stop(self):
        self.event.set()


为了测试我们的定时器是否能够正常工作, 定义一个测试函数:

def functest(args):
    print 'hello world , this is ' , args[0]  # 
测试函数的形参统一设定为一个元组。 设置元组原因:

1 元组对数据具有不可修改的保护特性

2 元组可适应动态,多参数传递的需求。将传递的参数统一打包处理, 无需对 Pysettimer() 类接口进行修改


运行测试函数:

#==================================================
def main():
    mytime=Pysettimer(functest, ('python ' ,'program ')) #multiple ,dynamic argument wouldnot affect  Pysettimer class API port

    mytime.start()
    
    time.sleep(10)      # append the main thread 
    mytime.stop()       # end the timer thread . 
    print 'time over'


if __name__=='__main__':
    main()


附上源文件及模块调用方法:

http://download.csdn.net/detail/hesiyuan4/6929521


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值