ScheduledExecutorService延时执行
时间: 2023-12-29 12:26:42 浏览: 53
ScheduledExecutorService是一个用于延时执行任务的线程池。它可以在指定的延迟时间后执行任务,也可以按照固定的时间间隔重复执行任务。下面是两使用ScheduledExecutorService延时执行任务的例子:
1. 使用ScheduledExecutorService执行次延时任务:
```java
import java.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class DelayedTaskExample {
public static void main(String[] args) {
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
Runnable task = () -> {
// 执行需要延时执行的任务
System.out.println("Delayed task executed.");
};
int delay = 5; // 延迟时间为5秒
executor.schedule(task, delay, TimeUnit.SECONDS);
executor.shutdown();
}
}
```
2. 使用ScheduledExecutorService重复执行延时任务:
```java
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class RepeatedTaskExample {
public static void main(String[] args) {
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
Runnable task = () -> {
// 执行需要重复执行的任务
System.out.println("Repeated task executed.");
};
int initialDelay = 2; // 初始延迟时间为2秒
int period = 3; // 重复执行的时间间隔为3秒
executor.scheduleAtFixedRate(task, initialDelay, period, TimeUnit.SECONDS);
//executor.shutdown();
}
}
```
这两个例子分别展示了使用ScheduledExecutorService执行一次延时任务和重复执行延时任务的方法。你可以根据自己的需求选择适合的方式来延时执行任务。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)