package com.huangbei.test2;
import lombok.extern.slf4j.Slf4j;
import java.time.DayOfWeek;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/*
固定时间执行任务,比如,每周星期四中午12:30
*/
@Slf4j(topic = "c.Test-ScheduledThreadPool")
public class Test14 {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
LocalDateTime nextTime = now.withNano(0).withSecond(0).withMinute(30).withHour(12).with(DayOfWeek.MONDAY);
// LocalDateTime newTime = now.withNano(0).withSecond(0).withMinute(0).withHour(18).plusDays(DayOfWeek.SUNDAY.getValue()-now.getDayOfWeek().getValue());
//合法性检测
if (now.compareTo(nextTime) > 0) {
nextTime = nextTime.plusWeeks(1);
}
log.debug("当前时间:{}", now);
log.debug("新时间:{}", nextTime);
ScheduledExecutorService pool = Executors.newScheduledThreadPool(2);
long initialDelay = Duration.between(now, nextTime).toMillis();
long period = 1 * 1000 * 60 * 60 * 24 * 7;
log.debug("initialDelay={}", initialDelay);
pool.scheduleAtFixedRate(() -> {
log.debug("到了执行的时间,执行这个任务...");
}, initialDelay, period, TimeUnit.MILLISECONDS);
}
}
注意
- LocalDateTime是不可变类,每一次修改都是新的值,修改后应重新赋值。