You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python不同函数调用间添加延迟的简化实现方案咨询

解决方案

方案1:封装通用调度函数(推荐,复用性最高)

这是适用场景最广的方案,无需修改原有函数,仅在批量调用时增加延迟逻辑,同时支持带参数的函数调用:

import time

def run_with_interval(delay: float, *funcs, run_last_delay: bool = True):
    """
    按顺序执行传入的函数,执行间隔为指定时长
    :param delay: 间隔秒数
    :param funcs: 待执行的函数序列,带参数的函数可通过lambda包裹传入
    :param run_last_delay: 最后一个函数执行完成后是否仍添加延迟,默认与原逻辑一致为True
    """
    for idx, func in enumerate(funcs):
        func()
        if not run_last_delay and idx == len(funcs) - 1:
            break
        time.sleep(delay)

调用方式非常简洁:

# 无参数函数直接传入即可
run_with_interval(1, my_func1, my_func2, my_func3)

# 带参数的函数用lambda包裹即可正常传入
def my_func_with_args(msg: str):
    print(msg)

run_with_interval(1, my_func1, lambda: my_func_with_args("测试参数"), my_func3)

方案2:遍历执行(适合一次性调用场景)

如果不需要复用逻辑,仅单次批量调用,可以直接遍历函数列表,仅需几行代码即可实现:

import time

delay = 1
for func in [my_func1, my_func2, my_func3]:
    func()
    time.sleep(delay)

两种方案均不会对原有函数造成任何侵入性修改,单独调用单个函数时不会附加延迟逻辑,完全匹配需求。


内容的提问来源于stack exchange,提问作者Mateusz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 08:24:01