ScheduledExecutorServiceExample
时间: 2024-06-19 13:01:35 浏览: 14
ScheduledExecutorService是Java并发包中的一个接口,它提供了一种在给定延迟后执行任务,或者定期执行任务的方式。下面是一个简单的示例,展示了如何使用ScheduledExecutorService来定时执行任务:
```java
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class ScheduledExecutorServiceExample {
public static void main(String[] args) {
// 创建一个ScheduledExecutorService实例,这里使用的是单线程的ScheduledThreadPoolExecutor
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
// 定义一个Runnable任务
Runnable task = () -> {
System.out.println("Task executed at: " + LocalDateTime.now());
};
// 每5秒执行一次任务,延迟1秒开始执行
executor.scheduleAtFixedRate(task, 1, 5, TimeUnit.SECONDS);
// 等待一段时间,然后关闭executor以释放资源
try {
Thread.sleep(30 * 1000); // 休眠30秒
} catch (InterruptedException e) {
e.printStackTrace();
}
executor.shutdown(); // 关闭executor
}
}
```
在这个例子中,`scheduleAtFixedRate`方法用于定期执行任务,它接受四个参数:初始延迟(这里是1秒),周期(这里是5秒),时间单位(这里是Seconds),以及任务实例。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)