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
         
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。如有问题,欢迎交流
原文地址:https://www.cnblogs.com/first-semon/p/8590598.html