在Python中,可以使用concurrent.futures.ThreadPoolExecutor
来创建线程池,并通过自定义回调函数在每10个任务完成后添加延时。以下是一个示例代码:
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
def task(n):
print(f"Task {n} started")
time.sleep(1) # 模拟任务执行时间
print(f"Task {n} completed")
return n
def callback(future):
future.result() # 确保任务完成
nonlocal count
count += 1
if count % 10 == 0:
print(f"Pausing for 5 seconds after completing {count} tasks")
time.sleep(5) # 延时5秒
count = 0
with ThreadPoolExecutor(max_workers=5) as executor:
futures = [executor.submit(task, i) for i in range(50)]
for future in as_completed(futures):
future.add_done_callback(callback)
threading.Lock
)等机制来解决。通过上述代码和解释,您可以在Python线程池执行中为每10个完成的任务添加延时。
领取专属 10元无门槛券
手把手带您无忧上云