Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/selenium/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在java中设置等待/睡眠的超时阈值?_Java_Selenium - Fatal编程技术网

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

如何在java中设置等待/睡眠的超时阈值?,java,selenium,Java,Selenium,我的任务很简单,使用selenium从url下载文件。在点击下载部分之前,我一直是这样做的。现在我想等到文件下载完毕。好的。我用下面的方法完成 do { Thread.sleep(60000); } while ((downloadeBuild.length()/1024) < 138900); do{ 睡眠(60000); } 而((downloadeBuild.length()/1024)

我的任务很简单,使用selenium从url下载文件。在点击下载部分之前,我一直是这样做的。现在我想等到文件下载完毕。好的。我用下面的方法完成

do {
    Thread.sleep(60000);
}
while ((downloadeBuild.length()/1024) < 138900);
do{
睡眠(60000);
}
而((downloadeBuild.length()/1024)<138900);
现在的挑战是我要等多久?我可以设置一些阈值吗?我能想到的是在do while中使用一个计数器,并检查直到计数器变为10或类似的值?但是Java中还有其他方法吗?因此,在下载文件之前,我没有任何操作要做

您可以使用

Stopwatch Stopwatch=Stopwatch.createStarted();
而((downloadeBuild.length()/1024)<138900&&topWatch.appead(TimeUnit.SECONDS)<60);
这个怎么样

我认为使用
TimeOut
是不稳定的,因为不需要等待不可预测的下载操作

您只需转到
CompletableFuture
使用
supplyAsync
进行下载,然后使用
然后应用
进行处理/转换并通过
join
检索结果,如下所示:

public class SimpleCompletableFuture {
    public static void main(String... args) {
        testDownload();
    }

    private static void testDownload() {
        CompletableFuture future = CompletableFuture.supplyAsync(() -> downloadMock())
                .thenApply(SimpleCompletableFuture::processDownloaded);
        System.out.println(future.join());
    }

    private static String downloadMock() {
        try {
            Thread.sleep(new Random().nextInt() + 1000); // mock the downloading time;
        } catch (InterruptedException ignored) {
            ignored.printStackTrace();
        }
        return "Downloaded";
    }

    private static String processDownloaded(String fileMock) {
        System.out.println("Processing " + fileMock);
        System.out.println("Done!");
        return "Processed";
    }
}

如果您想要的是暂停练习,您可以尝试以下代码:

    long timeout = 10 * 60 * 1000;
    long start = System.currentTimeMillis();
    while(System.currentTimeMillis() - timeout <= start ){
        //Not timeout yet, wait
    }
    //Time out, continue
long timeout=10*60*1000;
长启动=System.currentTimeMillis();

(System.currentTimeMillis()-timeout)是否尝试异步下载该文件?下载后使用
CompletableFuture
thenApply
如何?谢谢Hearen,我对这些功能不太熟悉,但肯定会有一些想法。同时,如果您能提供一些示例帮助,它会有所帮助。
    long timeout = 10 * 60 * 1000;
    long start = System.currentTimeMillis();
    while(System.currentTimeMillis() - timeout <= start ){
        //Not timeout yet, wait
    }
    //Time out, continue