如何在java中非常精确的时间发送http请求

xu3bshqb  于 2021-07-12  发布在  Java
关注(0)|答案(2)|浏览(411)

我想在一个非常精确的时间窗口(例如从20.08.2020 00.00.00到20.08.2020 00.00.50)中发送几个并行的http请求(例如通过async okhttp)。
http://www.quartz-scheduler.org has 精度高达1秒。
如何安排?

xurqigkl

xurqigkl1#

如果您关心服务器接收它们的时间,而不是客户机开始发送的时间,那么您应该使用一些请求来预热okhttp。
对于http/1.1连接,您需要多个连接。检查连接池大小,并根据需要进行调整。
对于http/2连接,当您转到发送结果时准备就绪。如果您担心任何一个请求的大小,您可能希望通过拥有多个客户机示例来覆盖okhttp的默认行为,以避免共享套接字上的行首阻塞。
如上所述,对于java线程调度,使用scheduledexecutorservice,并且可能在事件之前唤醒并旋转到精确的毫秒。你不能使用纳米时间,因为它与一个任意的历元有关,所以毫秒精度可能是你能做的最好的。

7ajki6be

7ajki6be2#

您可以在completablefuture中使用java调度任务来调度您的任务:类似这样的方法来调度您的http任务:
timeunit可用于调度到毫秒。(timeunit.millishes)

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;
}

有关completablefuture的概念,请参阅本文:
https://www.artificialworlds.net/blog/2019/04/05/scheduling-a-task-in-java-within-a-completablefuture/
或者,您可以编写自己的计划程序:
https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/scheduledexecutorservice.html
编辑:
尝试使用以下命令:schedulewithfixeddelay(runnable命令,long initialdelay,long delay,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);

相关问题