开发场景:
例如:使用java ScheduledThreadPoolExecutor定时线程池执行任务,只执行一次
java代码
@Test
public void test2() {
ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(1);
//指定时间执行一次
LocalDateTime date = LocalDateTime.of(2022, 5, 30, 17, 55, 2);
scheduledThreadPoolExecutor.schedule(
() -> System.out.println("开始执行时间========:" + (new Date())),
//加1是因为执行时间会比你指定时间提前1秒
LocalDateTime.now().until(date, ChronoUnit.SECONDS) + 1,
//指定单位秒
TimeUnit.SECONDS);
//异步取消任务执行,如果中途需要取消执行
new Thread(() -> {
try {
Thread.sleep(20000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("取消执行========:" + (new Date()));
future.cancel(true);
}).start();
try {
//等待异步定时线程完成,自己手动停止
Thread.sleep(600000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}