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() 

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

 

转载于:https://www.cnblogs.com/first-semon/p/8590598.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值