码迷,mamicode.com
首页 > 编程语言 > 详细

python 定时器

时间:2015-02-08 06:49:26      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:python 定时器

__author__ = ‘root‘
import time
from CTimeHandle import CTimeHandle
class RepeatableTimer(object):

    def __init__(self, interval, function, args=[], kwargs={}):
        self.interval = interval
        self.function = function
        self.args = args
        self.kwargs = kwargs
        self.dayrun=False
        self.afterhour=0
        self.mytime = CTimeHandle()
        self.myday=-1

    def setDailyRum(self,afterhour=0):
        self.afterhour=afterhour
        self.dayrun=True

    def cancelDailyRun(self):
        self.dayrun=False

    def cheakDailyRun(self):
        now = self.mytime.updateNow()
        print now
        year,mon,day =self.mytime.GetDateinfo()
        hour,min,sec = self.mytime.GetTimeinfo()

        if self.myday == day:
            return False

        self.myday = day
        print "hour %s,afterhour %s,day %s,myday %s"%(hour,self.afterhour,day,self.myday)
        if int(hour) > self.afterhour:
            return True

        return False



    def start(self):
        self.stop()
        import threading
        self._timer = threading.Timer(self.interval, self._run)
        self._timer.setDaemon(True)
        self._timer.start()

    def restart(self):
        self.start()

    def stop(self):
        if self.__dict__.has_key("_timer"):
            self._timer.cancel()
            del self._timer

    def _run(self):
        try:
            if self.dayrun and False == self.cheakDailyRun():
               pass
            else:
                self.function(*self.args, **self.kwargs)
        except:
            pass
        self.restart()

def Myfun(*args,**kargs):
    print "Myfun run"
    value = kargs[‘key1‘]+kargs[‘key2‘]
    print value


if __name__=="__main__":
    hash={‘key1‘:1,‘key2‘:2}

    c = RepeatableTimer(2,Myfun,"",hash)
    c.setDailyRum(24)
    c.start()
    time.sleep(3000)


本文出自 “风清扬song” 博客,请务必保留此出处http://2309998.blog.51cto.com/2299998/1612730

python 定时器

标签:python 定时器

原文地址:http://2309998.blog.51cto.com/2299998/1612730

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!