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

如何让Python函数foo()每隔10秒精确启动执行?

实现foo()每隔10秒精确启动的两种方案

嘿,你说得没错,要实现精确每隔10秒启动foo(),确实需要用线程把foo的执行和定时逻辑分开——毕竟原来的代码是等foo跑完才开始计时,自然会把foo的耗时也算进间隔里。下面给你两种实用的实现方式:

方案一:主线程控制定时,线程执行foo

这种方式的核心是记录每次启动foo的时间点,然后计算下一次启动需要等待的时长,确保不管foo跑多久,下一次启动都刚好和上一次间隔10秒。

代码示例:

import time
import threading
import random

def foo():
    # 模拟1-3秒的随机执行耗时
    run_time = random.randint(1, 3)
    print(f"{time.strftime('%H:%M:%S')} - foo开始执行,预计耗时{run_time}秒")
    time.sleep(run_time)
    print(f"{time.strftime('%H:%M:%S')} - foo执行完成")

if __name__ == "__main__":
    last_start_time = time.time()
    while True:
        # 启动线程执行foo,不阻塞主线程
        threading.Thread(target=foo).start()
        # 计算下一次启动需要等待的时间:10秒减去当前到上次启动的时间差
        next_wait = 10 - (time.time() - last_start_time)
        # 如果计算出的等待时间为正(避免foo执行超过10秒的极端情况),就等待
        if next_wait > 0:
            time.sleep(next_wait)
        # 更新上次启动时间为当前时间
        last_start_time = time.time()

方案二:用Threading.Timer递归调度

这种方式更简洁,利用threading.Timer实现定时触发,每次启动foo的同时,就调度10秒后再次触发下一次执行,完全不用手动计算时间差。

代码示例:

import time
import threading
import random

def foo():
    # 模拟1-3秒的随机执行耗时
    run_time = random.randint(1, 3)
    print(f"{time.strftime('%H:%M:%S')} - foo开始执行,预计耗时{run_time}秒")
    time.sleep(run_time)
    print(f"{time.strftime('%H:%M:%S')} - foo执行完成")

def schedule_foo():
    # 启动线程执行foo
    threading.Thread(target=foo).start()
    # 调度10秒后再次执行schedule_foo,实现循环触发
    threading.Timer(10, schedule_foo).start()

if __name__ == "__main__":
    # 首次启动调度
    schedule_foo()
    # 主线程保持运行(否则程序会直接退出)
    while True:
        time.sleep(1)

注意事项

  • 两种方案都用线程执行foo,确保foo的耗时不会干扰定时逻辑;
  • 如果foo可能抛出异常,建议在foo内部加上try-except块,避免单个foo执行失败导致整个调度逻辑中断;
  • 方案二中的主线程需要保持运行,否则定时器会随主线程退出而失效,因此加了一个无限sleep的循环。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:22:38