Python 中高级知识 threading Timer

Timer

Timer 是threading模块里面的一个类,主要是做简单的定时任务。适用于设置一段时间后执行某一种逻辑的场景。更加专业的计划任务其实Timer不能胜任,应该是sched,不过一般场景我们使用Timer也够用

源码

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

python给了说明: 传入function作为将要执行的逻辑体,并传入可变和关键字参数,设置多少时间后执行。构造完毕后,直接start()执行即可,如果你想取消计划,也可以使用cancel()取消,但是前提是这个timer在你取消的时候,是未开始运行的,如果已经在运行中了,就无法取消了

使用

使用起来很简单

# !/usr/bin/env python3
# -*- coding: utf-8 -*
from threading import Timer
 
 
def timer_test(s: str):
    print(s)
 
 
= Timer(30.0, timer_test, ("Hello Python",))
t.start()

实际的逻辑会在30s后开始执行

 
posted @ 2021-09-26 10:41  旁人X  阅读(789)  评论(0)    收藏  举报