Reputation: 3548
I make a request to download a file from server. The thing is the file is being generated on the server-side and the generation is asynchronous.
Initially I did something like
try {
Thread.sleep(10000);
} catch (Exception e) {
//TODO
}
and then I do something with the newly downloaded file.
The problem is sometimes it takes more than 10s to generate the file and sometimes it takes less. So my "test" will randomly pass or fail.
My first attempt was to do repeated requests(every 1000 millis) until I find the file in the server and have a timeout after say 2 minutes. But I think this is really bad design.
So, what is the best way to wait for the file to be generated and then download it?
EDIT: I use http communication.
Upvotes: 2
Views: 658
Reputation: 4712
What about a blocking I/O operation?
Something like this:
http://docs.oracle.com/javase/6/docs/api/java/io/InputStream.html
How do you communicate with the remote server? Socket? HTTP?
Edit for HTTP: If you also have access to the server side, you could just send an HTTP header with the content-length of the file even though it's not created so the client gets "hooked up" until it's actually created. Be careful with the timeout too. And you could also output (transfer) the file directly (not wait that it's done) that would get rid of the timeout problem I guess.
Upvotes: 1
Reputation: 262714
Unless you have some way to receive notifications (like Amazon does for its background jobs), polling is pretty much the only thing you can do.
If it is just seconds you are talking about (and not minutes or hours), and you control the server-side, you can have the request processing block until the file is created.
Upvotes: 1