实现延时执行一个函数的功能


import threading
import time


class FakeTimer(object):

    def __init__(self, interval, function, args=(), kwargs={}):

        self.interval = interval
        self.function = function
        self.args = args
        self.kwargs = kwargs
        self.event = threading.Event()

    def start(self):
        threading.Thread(name='run', target=self._run).start()

    def cancel(self):
        self.event.set()
        print('Job is canceled')

    def _run(self):
        if not self.event.wait(self.interval):
            threading.Thread(name='job', target=self.function, args=self.args, kwargs=self.kwargs).start()


def add(x, y):
    print(x + y)


t = FakeTimer(10, add, (4, 5))
t.start()
time.sleep(5)
t.cancel()


文档更新时间: 2021-10-04 00:19   作者:闻骏