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\n'

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\n'
    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() 

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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM