装饰器使用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