Python decorator来计划函数的执行

Python decorator来计划函数的执行,python,python-decorators,Python,Python Decorators,我需要编写一个带有参数的Python decorator来调度函数的执行 我尝试编写一个返回装饰器的函数,但没有成功: 导入时间 def计划(持续时间): def装饰器(功能): 睡眠时间(持续时间) def新功能(*args,**kwargs): 返回函数(*args,**kwargs) 返回新函数 返回装饰器 @附表(1) def hello(): 打印(“你好,世界!”) 开始=时间。时间() 你好() 打印(f'执行时间{round(time.time()-start,2)}s') 输

我需要编写一个带有参数的Python decorator来调度函数的执行

我尝试编写一个返回装饰器的函数,但没有成功:

导入时间
def计划(持续时间):
def装饰器(功能):
睡眠时间(持续时间)
def新功能(*args,**kwargs):
返回函数(*args,**kwargs)
返回新函数
返回装饰器
@附表(1)
def hello():
打印(“你好,世界!”)
开始=时间。时间()
你好()
打印(f'执行时间{round(time.time()-start,2)}s')
输出

Hello, world!
Execution took 0.0s
我希望函数在1s后执行,如何实现它?

时间。睡眠(持续时间)
应该在内部函数中,如下所示:

def计划(持续时间):
def装饰器(功能):
def新功能(*args,**kwargs):
睡眠时间(持续时间)
返回函数(*args,**kwargs)
返回新函数
返回装饰器

现在,它应该可以使用time.sleep延迟并阻止执行,因此您的装饰器更像是@wait,而不是@scheduled。您可以在decorator中使用线程来实现真正的调度。