import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class DynamicScheduler {
public static void main(String[] args) {
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
// 初始延迟后执行第一次
executor.schedule(new Runnable() {
@Override
public void run() {
try {
doWork();
} finally {
// 计算下一次执行的时间并重新调度
long delayUntilNextExecution = calculateDelayUntilNextExecution();
executor.schedule(this, delayUntilNextExecution, TimeUnit.MILLISECONDS);
}
}
}, 0, TimeUnit.MILLISECONDS);
// 防止主线程退出,确保executor可以运行
Runtime.getRuntime().addShutdownHook(new Thread(() -> executor.shutdown()));
}
private static void doWork() {
System.out.println("Doing work at " + System.currentTimeMillis());
// 这里执行你的任务逻辑
}
private static long calculateDelayUntilNextExecution() {
// 根据你的业务逻辑计算延迟
// 例如,假设你想在每个整点执行
long now = System.currentTimeMillis();
long nextHour = ((now / 1000 / 60 / 60) + 1) * 1000 * 60 * 60;
return nextHour - now;
}
}