java - 如何在java中设置等待/睡眠的超时阈值?

我的任务很简单,使用 selenium 从 url 下载文件。我一直在点击下载部分。现在我想等到文件下载完毕。很好。我使用以下并完成。


do {

    Thread.sleep(60000);

}

while ((downloadeBuild.length()/1024) < 138900);

现在的挑战是我要等多久?我可以设置一些阈值吗?我能想到的是在 do while 中使用计数器并检查直到计数器变为 10 或类似的东西?但是在 Java 中还有其他方式吗?因此,在下载文件之前,我没有任何操作要做。


青春有我
浏览 221回答 3
3回答

慕姐4208626

这个怎么样?我认为使用TimeOut不稳定,因为不需要等待不可预测的下载操作。您可以转为CompletableFutureusingsupplyAsync进行下载并用于thenApply进行处理/转换并通过join如下方式检索结果:public class SimpleCompletableFuture {&nbsp; &nbsp; public static void main(String... args) {&nbsp; &nbsp; &nbsp; &nbsp; testDownload();&nbsp; &nbsp; }&nbsp; &nbsp; private static void testDownload() {&nbsp; &nbsp; &nbsp; &nbsp; CompletableFuture future = CompletableFuture.supplyAsync(() -> downloadMock())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .thenApply(SimpleCompletableFuture::processDownloaded);&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(future.join());&nbsp; &nbsp; }&nbsp; &nbsp; private static String downloadMock() {&nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Thread.sleep(new Random().nextInt() + 1000); // mock the downloading time;&nbsp; &nbsp; &nbsp; &nbsp; } catch (InterruptedException ignored) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ignored.printStackTrace();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return "Downloaded";&nbsp; &nbsp; }&nbsp; &nbsp; private static String processDownloaded(String fileMock) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Processing " + fileMock);&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Done!");&nbsp; &nbsp; &nbsp; &nbsp; return "Processed";&nbsp; &nbsp; }}

翻过高山走不出你

如果您想要的是超时练习,您可以尝试以下代码:&nbsp; &nbsp; long timeout = 10 * 60 * 1000;&nbsp; &nbsp; long start = System.currentTimeMillis();&nbsp; &nbsp; while(System.currentTimeMillis() - timeout <= start ){&nbsp; &nbsp; &nbsp; &nbsp; //Not timeout yet, wait&nbsp; &nbsp; }&nbsp; &nbsp; //Time out, continue这在java库中很常见。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java