zoukankan      html  css  js  c++  java
  • python中定时任务

    今天看网络框架时,突然想看一下定时器,于是往上搜索了一下python中timer task的实现,但是由于python本身对线程的支持不是太好,因为全局排它锁的存在,使得多线程在访问资源时效率比较低。下面来提一下网上普遍使用的timer类的thread实现方法。

    #-*-coding:utf-8-*-
    import threading
    
    def doTask():
        print 'hello'
    
    timer=threading.Timer(1,doTask)
    timer.start()

    输出结果:

    hello

    既然是定时任务,为什么不循环执行呢?

    因为代码只执行了一遍,怎么可能输出多行!

    改一下就OK了:

    #-*-coding:utf-8-*-
    import threading
    
    def doTask():
        print 'hello
    '
    
    if __name__=='__main__':
        while True:
            timer=threading.Timer(1,doTask)
            timer.start()

    不过这是一个死循环。很不好,另一种笨笨方法:

    #-*-coding:utf-8-*-
    import threading
    from time import sleep
    
    def doTask():
        print 'hello
    '
        timer=threading.Timer(1,doTask)
        timer.start()
    
    timer=threading.Timer(1,doTask)
    timer.start()
            

    本人不推荐这么使用定时,下面来介绍一些第三方中的定时任务类:Twisted中的Task.

    from twisted.internet import task
    import logging
    class MyTimeTask(object):
        def __init__(self):
            self.taskName='task'
        
        def myPrint(self):
            print self.taskName
            
        def onTime(self):
            try:
                self.myPrint()
            except Exception:
                logging.error('print fasiled!')
        
        def starTask(self):
            temp=task.LoopingCall(self.onTime)   
            temp.start(1, True) 
            
    instance=MyTimeTask()
    instance.starTask() 

    框架定时任务完毕。谢谢阅读

    作者:first_semon
             
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。如有问题,欢迎交流
  • 相关阅读:
    Go基础数据类型
    在foreach中使用distinct查找不重复记录
    DataTable,List去重复记录的方法(转载)
    ArcEngine的IMap接口(转载)
    根据Excel表格建立Shp文件(开发详解及源代码)(转载)
    axmapcontrol和mapcontrol有什么区别呢(转发)
    DataSet多表查询操作(转载)
    c#调用DLL(转载)
    wall 系列技术贴
    ArcEngine的IFeaturLayer接口(转载)
  • 原文地址:https://www.cnblogs.com/first-semon/p/8590598.html
Copyright © 2011-2022 走看看