如何解决如何在JAVA中的非常精确的时间发送HTTP请求
我想在非常精确的时间窗口(例如,从20.08.2020 00.00.00到20.08.2020 00.00.50)发送多个并行HTTP请求(例如,通过异步OkHttp)。
http://www.quartz-scheduler.org的精度最高为1秒。
如何安排他们?
解决方法
如果您关心服务器接收消息的时间,而不是客户端开始发送消息的时间,则应该对OkHttp进行一些请求预热。
对于HTTP / 1.1连接,您需要多个连接。检查连接池的大小,并在需要时进行调整。
当您要发送结果时准备好HTTP / 2连接。如果您担心任何一个请求的大小,则可能希望通过具有多个客户端实例来避免OkHttp的默认行为,以避免共享套接字上的行头阻塞。
如上所述,对于Java线程调度,请使用ScheduledExecutorService并可能在事件之前唤醒并旋转直到确切的毫秒。您无法使用nanoTime,因为它与任意时期有关,因此毫秒精度可能是您可以做到的最好的结果。
,您可以在CompletableFuture中使用Java计划任务来计划任务: 这样的事情可以安排您的http任务:
TimeUnit可用于安排直到毫秒的时间。(TimeUnit.MILLISECONDS)
public static <T> CompletableFuture<T> schedule(
ScheduledExecutorService executor,Supplier<T> command,long delay,TimeUnit unit
) {
CompletableFuture<T> completableFuture = new CompletableFuture<>();
executor.schedule(
(() -> {
try {
return completableFuture.complete(command.get());
} catch (Throwable t) {
return completableFuture.completeExceptionally(t);
}
}),delay,unit
);
return completableFuture;
}
有关可完成的未来的概念,请参阅本文:
或者您可以编写自己的调度程序:
https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledExecutorService.html
编辑:
尝试使用此方法: scheduleWithFixedDelay(可运行命令,长initialDelay,长延迟,TimeUnit单位)
ZonedDateTime now = ZonedDateTime.now(ZoneId.of("America/Los_Angeles"));
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");
LocalDateTime ldt= LocalDateTime.parse("2020-10-17T12:42:04.000",formatter);
ZonedDateTime nextRun= ldt.atZone(ZoneId.of("America/Los_Angeles"));
if(now.compareTo(nextRun) > 0)
nextRun = nextRun.plusDays(1);
Duration duration = Duration.between(now,nextRun);
long initalDelay = duration.toMillis();
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(new MyRunnableTask(),initalDelay,TimeUnit.DAYS.toMillis(1),TimeUnit.MILLISECONDS);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。