定时任务

代码

public class TestSchedule {
    //如何让每周四18:00:00定时执行任务
    public static void main(String[] args) {
        //获取当前时间
        LocalDateTime now = LocalDateTime.now();
        System.out.println(now);
        //获取周四时间
        LocalDateTime time = now.withHour(16).withMinute(0).withSecond(0).withNano(0).with(DayOfWeek.THURSDAY);
        if (now.compareTo(time) > 0) {
            time=time.plusWeeks(1);
        }
        //initialDelay代表当前时间和周四的差值
        long millis = Duration.between(now, time).toMillis();
        //一周时间
        long period = 1000 * 60 * 60 * 24 * 7;
        ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
        pool.scheduleAtFixedRate(() -> {
            System.out.println("running");
        },millis , period, TimeUnit.MILLISECONDS);
    }
posted @ 2020-09-07 09:11  清风5438  阅读(104)  评论(0编辑  收藏  举报