注意点

main一启动就产生一个线程

计划任务可以直接用main线程

所有线程池核心设置为1个即可,否则会产生很多线程,浪费资源

JVM调优图

Java定时任务计划:每周某个特定时间执行,使用scheduleAtFixedRate与线程池_线程池

//每周某个特定时间执行
public class ScheduledDay {
public static void main(String[] args) {
//获取当前时间
LocalDateTime now = LocalDateTime.now();
//获取目标时间(周一,03:59)
LocalDateTime target = now.with(DayOfWeek.MONDAY).withHour(3).withMinute(59).withSecond(0).withNano(0);
//如果当前时间>本周目标时间,排除本周,找下周
if (now.compareTo(target) > 0) {
target = target.plusWeeks(1);
}
//差值
long initialDelay = Duration.between(now, target).toMillis();
//间隔时间——每周
long period = 1000 * 60 * 60 * 24 * 7;
ScheduledExecutorService pool = scheduledExecutorService();
pool.scheduleAtFixedRate(() -> {
System.out.println(LocalDateTime.now() + "执行任务");
}, initialDelay, period, TimeUnit.MILLISECONDS);
}

//线程池
public static ScheduledExecutorService scheduledExecutorService() {
return new ScheduledThreadPoolExecutor(
1,
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.CallerRunsPolicy()
);
}
}