Python 调度函数执行的装饰器
Python decorator to schedule the execution of a function
我需要编写一个 Python 带有参数的装饰器来安排函数的执行。
我尝试编写一个 returns 装饰器的函数,但没有成功:
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
我希望函数在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
现在应该可以了
我需要编写一个 Python 带有参数的装饰器来安排函数的执行。
我尝试编写一个 returns 装饰器的函数,但没有成功:
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
我希望函数在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
现在应该可以了