线程池应用
实现:
每个星期四19点定期执行
直接上代码:
public class Main {
public static void main(String[] args) throws Exception{
ScheduledExecutorService pool = Executors.newScheduledThreadPool(2);
// 获取当前时间
LocalDateTime now = LocalDateTime.now();
// 获取本周四的时间
LocalDateTime time = now.withHour(19).withMinute(0).withSecond(0).withNano(0).with(DayOfWeek.THURSDAY);
// 如果当前时间 > 本周四,就时间设置为下一周的周四
if (now.compareTo(time) > 0){
time = time.plusWeeks(1);
}
// 得到延时执行的时间
long initDelay = Duration.between(now, time).toMillis();
// 得到执行时间间隔
long preiod = 1000 * 60 * 60 * 24 * 7;
pool.scheduleAtFixedRate(()->{
System.out.println("执行");
},initDelay,preiod,TimeUnit.MILLISECONDS);
}
}