python 定时器 ,还是很好玩的

Posted 77 months ago python threading timer 定时器

上代码!


from threading import Timer

##循环loop定时器
class LoopTimer(Timer):
    def __init__(self, interval, function, args=[], kwargs={}):
        Timer.__init__(self, interval, function, args, kwargs)
    def run(self):
        while True:
            self.finished.wait(self.interval)
            if self.finished.is_set():
                self.finished.set()
                break
            self.function(*self.args, **self.kwargs)
    #定时执行注解
    def delayed(seconds):
        def decorator(f):
            def wrapper(*args, **kargs):
                t = LoopTimer(seconds, f, args, kargs)
                t.start()
            return wrapper
        return decorator

#单次定时器
class OneTimer(Timer):
    def __init__(self, interval, function, args=[], kwargs={}):
        Timer.__init__(self, interval, function, args, kwargs)

注意

要用的时候



def  a():
    print("aaa")


t = LoopTimer(1,a)

t.start()

#函数要不加括号

点击评论