示例: 在每周周四执行定时任务
package com.tian;
import java.time.DayOfWeek;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class TestSchedule {
private static LocalDateTime nowTime;
// 如何让每周四 18:00:00 定时执行任务?
public static void main(String[] args) {
LocalDateTime nextThursdayTime = getTheTimeOfNextThursday();
// initailDelay 代表当前时间和周四的时间差
// period 一周的间隔时间
long initailDelay = Duration.between(nowTime, nextThursdayTime).toMillis();
long period = 1000 * 60 * 60 * 24 * 7;
ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
pool.scheduleAtFixedRate(() -> {
System.out.println("running...");
}, initailDelay, period, TimeUnit.MILLISECONDS);
}
public static LocalDateTime getTheTimeOfNextThursday() {
// 获取当前时间
nowTime = LocalDateTime.now();
// 获取周四时间
LocalDateTime time = nowTime.withHour(18).withMinute(0).withSecond(0).withNano(0).with(DayOfWeek.THURSDAY);
// 如果 当前时间 > 本周周四
if (nowTime.compareTo(time) > 0) {
// time 加 1周, 为下周周四
time = time.plusWeeks(1);
}
return time;
}
}



