如何在Python中限时运行函数且不阻塞其他后台函数
实现限时运行的后台函数,不阻塞其他任务
要解决函数C运行指定时长后停止,同时函数A、B持续运行的问题,核心是将限时函数放到独立线程中执行,避免阻塞主线程或其他任务。你之前用time.time()结合while循环的思路没问题,但因为放在主线程才导致阻塞,改成线程即可解决。
方案1:函数内部计时退出
直接在函数C内部记录开始时间,循环检查是否达到运行时长,到点自动退出。同时把所有函数都放到独立线程,保证互不阻塞。
import threading import time def func_A(): while True: print("函数A正在运行...") time.sleep(1) # 避免CPU占用过高 def func_B(): while True: print("函数B正在运行...") time.sleep(1.5) def func_C(run_duration): start_time = time.time() while time.time() - start_time < run_duration: # 这里写函数C的业务逻辑 print("函数C正在运行...") time.sleep(0.8) print(f"函数C已运行{run_duration}秒,停止执行") if __name__ == "__main__": # 启动函数C的后台线程,daemon=True表示随主线程结束而终止 c_thread = threading.Thread(target=func_C, args=(5,), daemon=True) c_thread.start() # 启动A、B的线程 a_thread = threading.Thread(target=func_A, daemon=True) b_thread = threading.Thread(target=func_B, daemon=True) a_thread.start() b_thread.start() # 主线程保持运行,否则所有后台线程会随主线程退出 while True: time.sleep(1)
方案2:用事件+定时器控制退出
如果需要更灵活的终止控制(比如外部触发停止),可以用threading.Event结合定时器来结束函数C的运行:
import threading import time def func_A(): while True: print("函数A正在运行...") time.sleep(1) def func_B(): while True: print("函数B正在运行...") time.sleep(1.5) def func_C(stop_event): while not stop_event.is_set(): # 函数C的业务逻辑 print("函数C正在运行...") time.sleep(0.8) print("函数C已停止执行") if __name__ == "__main__": run_duration = 5 stop_c_event = threading.Event() # 启动函数C的线程 c_thread = threading.Thread(target=func_C, args=(stop_c_event,), daemon=True) c_thread.start() # 定时触发停止事件 threading.Timer(run_duration, stop_c_event.set).start() # 启动A、B线程 a_thread = threading.Thread(target=func_A, daemon=True) b_thread = threading.Thread(target=func_B, daemon=True) a_thread.start() b_thread.start() # 主线程保持存活 while True: time.sleep(1)
关键说明
- 所有函数都放在独立线程中,彻底避免单线程阻塞问题
daemon=True标记后台线程,主线程运行时它们会持续执行,主线程退出时会自动终止(如果需要A、B永久运行,保证主线程不退出即可)- 方案1适合简单的限时场景,方案2更灵活,支持外部干预停止函数C
内容的提问来源于stack exchange,提问作者Madhav Koduvayur
相关产品推荐
相关产品推荐

