Python装饰器来安排函数的执行时间

时间:2019-06-11 14:53:06

标签: python python-decorators

我需要编写一个带有参数的Python装饰器,以调度函数的执行。

我试图编写一个返回装饰器的函数,但是没有用:

import time


def scheduled(duration):
    def decorator(function):
        time.sleep(duration)
        def new_function(*args, **kwargs):
            return function(*args, **kwargs)
        return new_function
    return decorator


@scheduled(1)
def hello():
    print('Hello, world!')


start = time.time()
hello()
print(f'Execution took {round(time.time() - start, 2)}s')

输出

Hello, world!
Execution took 0.0s

我希望函数在1s之后执行,我如何实现它?

1 个答案:

答案 0 :(得分:1)

time.sleep(duration)行应位于内部函数内部,如下所示:

def scheduled(duration):
    def decorator(function):
        def new_function(*args, **kwargs):
            time.sleep(duration)
            return function(*args, **kwargs)
        return new_function
    return decorator

现在应该可以了