6

java | 定时任务

 1 year ago
source link: https://benpaodewoniu.github.io/2023/01/03/java166/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

java | 定时任务 | 犀牛的博客

姑苏城外一茅屋,万树梅花月满天

让程序每周四 18:00:00 定时执行任务。

package com.redisc;

import lombok.extern.slf4j.Slf4j;

import java.time.DayOfWeek;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Slf4j(topic = "c.Test")
public class Run {

public static void main(String[] args) throws InterruptedException, ExecutionException {
ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
// 获取当前时间
LocalDateTime now = LocalDateTime.now();
LocalDateTime time = now.withHour(18).withMinute(0).withSecond(0).withNano(0).with(DayOfWeek.THURSDAY);
// 如果当前时间 > 本周四,找下周时间
if (now.compareTo(time) > 0) {
time = time.plusWeeks(1);
}
// initialDelay 代表时间和周四的时间差
long initailDelay = Duration.between(now, time).toMillis();
long period = 1000 * 60 * 60 * 24 * 7;
pool.scheduleWithFixedDelay(() -> {
System.out.println("running...");
}, initailDelay, period, TimeUnit.MILLISECONDS);
}
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK