前言
有时我们需要定期执行某个程序,比如隔一段时间备份一下日志文件,查询或者更新某个数据等等,这时就需要写一个定时执行的功能。
一、定期执行
如何让每周日18:00:00定时执行任务?
@Test
public void testLocalDateTime() {
//获取当前时间
LocalDateTime now = LocalDateTime.now();
//获取本周四 18:00:00:000
LocalDateTime thursday = now.with(DayOfWeek.THURSDAY).withHour(18).withMinute(0).withSecond(0).withNano(0);
if(now.compareTo(thursday) >=0){
thursday = thursday.plusWeeks(1);
}
//计算时间差,即延时执行时间
long initialDelay = Duration.between(now, thursday).toMillis();
//计算每次执行的间隔时间,即一周的毫秒值
long oneWeek = 7 * 24 * 60 * 60 * 1000;
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(2);
System.out.println("开始时间:"+new Date());
executorService.scheduleAtFixedRate(() -> {
System.out.println("执行时间:" + new Date());
},initialDelay,oneWeek, TimeUnit.MILLISECONDS);
}