使用 while 循环的装饰器

decorator using while loop

假设我想重复执行任何功能 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'), timeout=5, interval=1)

输出为:

hello id3a
hello id3a
hello id3a
hello id3a
hello id3a