ThreadPoolExecutor 延迟执行
时间: 2024-01-11 16:22:48 浏览: 26
ThreadPoolExecutor可以通过使用ScheduledThreadPoolExecutor来实现延迟执行任务的功能。ScheduledThreadPoolExecutor是ThreadPoolExecutor的子类,它提供了一些额外的方法来支持延迟执行和周期执行任务。
下面是一个示例代码,演示了如何使用ScheduledThreadPoolExecutor来实现延迟执行任务:
```python
import threading
import time
def delayed_task():
print("Delayed task executed")
# 创建一个ScheduledThreadPoolExecutor对象
executor = threading.ThreadPoolExecutor()
# 延迟执行任务
executor.submit(delayed_task)
time.sleep(5) # 等待5秒钟
# 关闭线程池
executor.shutdown()
```
在上面的代码中,我们首先创建了一个ScheduledThreadPoolExecutor对象,然后使用submit()方法提交了一个延迟执行的任务。接着,我们使用time.sleep()方法来等待5秒钟,以确保任务被延迟执行。最后,我们调用shutdown()方法来关闭线程池。
请注意,ScheduledThreadPoolExecutor还提供了其他方法来支持周期执行任务,例如scheduleAtFixedRate()和scheduleWithFixedDelay()。你可以根据自己的需求选择适合的方法来实现延迟执行任务。