python循环定时任务

2020-11-16  本文已影响0人  Jessieee_Y

想要实现:一个函数 查看指定端口的进程是否运行正常。该函数需要每隔几分钟循环地执行。

Timer(interval, function, args=[], kwargs={})

最简单的方法就是在function中注册Timer, 每隔interval 产生一个线程,线程执行function,以达到循环的效果。interval的单位是秒。
示例:

from threading import Timer
def hello():
print "hello, world" 
   
t = Timer(10.0, hello) 
t.start() 

重写RepeatingTimer 类的run方法

在python2里的_Timer(相当于python3的Timer)是threading的子类。重写如下:

from threading import _Timer
def hello():
    print "hello, world"
class RepeatingTimer(_Timer): 
   def run(self):
       while not self.finished.is_set():
           self.function(*self.args, **self.kwargs)
           self.finished.wait(self.interval)
t = RepeatingTimer(10.0, hello)
t.start()

为了理解以上重写的RepeatingTimer,再看_Timer的原函数:

class _Timer(Thread):
    """Call a function after a specified number of seconds:
            t = Timer(30.0, f, args=[], kwargs={})
            t.start()
            t.cancel() # stop the timer's action if it's still waiting
    """
    def __init__(self, interval, function, args=[], kwargs={}):
        Thread.__init__(self)
        self.interval = interval
        self.function = function
        self.args = args
        self.kwargs = kwargs
        self.finished = Event()
    def run(self):
        self.finished.wait(self.interval)
        if not self.finished.is_set():
            self.function(*self.args, **self.kwargs)
        self.finished.set()
    def cancel(self):
        """Stop the timer if it hasn't finished yet"""
        self.finished.set()    
上一篇下一篇

猜你喜欢

热点阅读