一、Timer 与 TimerTask
1、基本介绍
- Timer 是 Java 提供的一个工具类,用于在后台线程中安排任务进行一次或重复固定的延迟执行,Timer 的内部实现使用了线程池来管理任务的执行,使得开发者能够方便地安排和管理定时任务,Timer 的主要方法如下
方法 | 说明 |
---|
schedule(TimerTask task, Date time) | 在指定时间执行指定任务 |
schedule(TimerTask task, Date firstTime, long period) | 在指定时间执行指定任务,之后每隔 period 毫秒执行一次 |
schedule(TimerTask task, long delay) | 在指定延迟之后执行指定任务 |
schedule(TimerTask task, long delay, long period) | 在指定延迟之后执行指定任务,之后每隔 period 毫秒执行一次 |
cancel() | 取消此计时器中的所有当前已安排的任务 |
- TimerTask 是一个抽象类,表示一个可以由 Timer 安排的一次性或重复执行的任务,开发者需要继承 TimerTask 并重写 run 方法来定义任务的具体内容
2、基本使用
- TimerAndTimerTaskTest.java
package com.my.timerandtimertask;
import java.util.Timer;
import java.util.TimerTask;
public class TimerAndTimerTaskTest {
public static void main(String[] args) {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("任务执行一次:Hello World");
}
}, 1000);
timer.schedule(new TimerTask() {
int count = 0;
@Override
public void run() {
count++;
System.out.println("任务执行多次(次数:" + count + "):Hello World");
}
}, 5000, 3000);
}
}
二、ScheduledExecutorService
- ScheduledExecutorService 是 Java 并发包(java.util.concurrent)中提供的一个接口,它继承自 ExecutorService 接口,并扩展了线程池的功能,允许在预定的时间执行任务,也可以周期性地重复执行任务
1、schedule
(1)基本介绍
- 在指定的延迟后执行一次任务
public ScheduledFuture<?> schedule(Runnable command,
long delay, TimeUnit unit);
- 在指定的延迟后执行一次任务,并返回一个可用于获取任务结果的 Future 对象
public <V> ScheduledFuture<V> schedule(Callable<V> callable,
long delay, TimeUnit unit);
(2)演示
- 演示代码 1
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
Runnable task = () -> {
System.out.println("Executing task at " + System.currentTimeMillis());
};
executor.schedule(task, 3, TimeUnit.SECONDS);
- 演示代码 2
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
Callable<String> task = () -> {
return "Hello World 2";
};
ScheduledFuture<String> future = executor.schedule(task, 3, TimeUnit.SECONDS);
System.out.println( future.get());
System.out.println("Hello World 1");
Hello World 2
Hello World 1
2、scheduleAtFixedRate
(1)基本介绍
- 在指定的初始延迟后开始执行任务,并以给定的时间间隔重复执行任务,即使任务执行时间超过指定的时间间隔,它仍然会按照固定的时间间隔重复执行
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
long initialDelay,
long period,
TimeUnit unit);
参数 | 说明 |
---|
command | 要执行的任务 |
initialDelay | 首次执行任务前的延迟时间 |
period | 连续执行任务之间的周期时间 |
unit | initialDelay 和 period 的时间单位 |
(2)演示
ScheduledExecutorService executor = Executors.newScheduledThreadPool(5);
Runnable task = () -> {
System.out.println("Executing task at " + System.currentTimeMillis());
};
executor.scheduleAtFixedRate(task, 1, 3, TimeUnit.SECONDS);
3、scheduleWithFixedDelay
(1)基本介绍
- 在指定的初始延迟后开始执行任务,并在每次执行完成后等待给定的延迟时间,然后再次执行任务,这种方法可以确保任务之间有固定的延迟间隔
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
long initialDelay,
long delay,
TimeUnit unit);
参数 | 说明 |
---|
command | 要执行的任务 |
initialDelay | 首次执行任务前的延迟时间 |
period | 连续执行任务之间的周期时间 |
unit | initialDelay 和 period 的时间单位 |
(2)演示
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
Runnable task = () -> {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("Executing task at " + System.currentTimeMillis());
};
executor.scheduleWithFixedDelay(task, 1, 2, TimeUnit.SECONDS);