文章目录
1. 定期执行
如何让每周四 18:00:00 定时执行任务?
public static void main(String[] args) {
// 获取当前时间
LocalDateTime now = LocalDateTime.now();
System.out.println(now);
// 获取周四时间
LocalDateTime time = now.withHour(18).withMinute(0).withSecond(0).withNano(0).with(DayOfWeek.THURSDAY);
// 如果我的当前时间>本周周四,那就找下周周四
if(now.compareTo(time) > 0){
time.plusWeeks(1);
}
System.out.println(time);
//
// System.out.println(Duration.between(now, time).toMillis());
/**
* initaliDelay 当前时间和周四的时间差
* period 一周的间隔时间
*
*/
long initaliDelay = Duration.between(now, time).toMillis();
long period = 1000*60*60*24*7;
ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
pool.scheduleAtFixedRate(()->{
},initaliDelay, period, TimeUnit.MILLISECONDS);
}