如何解决装饰器使用while循环
假设我要在5秒钟内重复执行任何功能。 我可以做这样的事情:
def any_function(name):
print(f"hello {name}")
import time
timeout = 5 # [seconds]
timeout_start = time.time()
while time.time() < timeout_start + timeout:
time.sleep(1) # optional,just to slow down execution
any_function("id3a") #could be any function
如果我想让此while循环可用于其他功能,我尝试使用装饰器-见下文-但它在第一次迭代后中断了while循环。
def decorator_function(original_function):
import time
timeout = 5 # [seconds]
timeout_start = time.time()
while time.time() < timeout_start + timeout:
def wrapper_function(*args,**kwargs):
time.sleep(1) # optional,just to slow down execution
return original_function(*args,**kwargs)
return wrapper_function
@decorator_function
def any_function(name):
print(f"hello {name}")
any_function("id3a")
你会怎么做?
解决方法
如果要使用装饰器,请参见以下工作示例:
import time
def scheduler(timeout=5,interval=0):
def decorator(function):
def wrapper(*args,**kwargs):
timeout_start = time.time()
while time.time() < timeout_start + timeout:
time.sleep(interval)
function(*args,**kwargs)
return wrapper
return decorator
@scheduler(timeout=5,interval=1)
def any_function(name):
print(f'hello {name}')
any_function('id3a')
它给出输出:
hello id3a
hello id3a
hello id3a
hello id3a
hello id3a
如果您要创建另一个函数来重复调用该函数,请参见以下示例:
import time
def scheduler(function,timeout=5,interval=0):
timeout_start = time.time()
while time.time() < timeout_start + timeout:
time.sleep(interval)
function()
def any_function(name):
print(f'hello {name}')
scheduler(lambda: any_function('id3a'),interval=1)
输出为:
hello id3a
hello id3a
hello id3a
hello id3a
hello id3a
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。