Mandar Kale
Mandar Kale

Reputation: 337

How to set a timeout threshold to wait/sleep in java?

My task is simple to download a file from a url using selenium. I did till clicking on the download part. Now I want to wait till the file is downloaded.Fine. I use following and done.

do {
    Thread.sleep(60000);
}
while ((downloadeBuild.length()/1024) < 138900);

Now challenge is for how much time do I wait ? Can I set some threshold ? I can think of is use a counter in do while and check till counter goes to 10 or something like that ? But any other way in Java ? As such I do not have any action to do till the file is downloaded.

Upvotes: 2

Views: 3106

Answers (3)

Eugene
Eugene

Reputation: 11055

If what you want is a time out practice, may be you can try code below:

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

It's quite common in java library.

Upvotes: 0

Hearen
Hearen

Reputation: 7828

How about this?

I think using TimeOut is not stable since there is no need to wait for a un-predictable downloading operation.

You can just turn to CompletableFuture using supplyAsync to do the downloading and use thenApply to do the processing/converting and retrieve the result by join as follows:

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

Upvotes: 4

Guy
Guy

Reputation: 50809

You can use guava Stopwatch

Stopwatch stopwatch = Stopwatch.createStarted();
while ((downloadeBuild.length()/1024) < 138900 && topWatch.elapsed(TimeUnit.SECONDS) < 60);

Upvotes: 2

Related Questions