> Hi,
>
> What would be the best way to code a task so that it would run
> iteratively for n seconds. For example, I have to code to fire a http
> request, but I want to fire that request over and over for 60 seconds.
So, your requirement (pseudo code)
for 60 second
make a request
in Java, that translates to
> I was thinking about grabbing the time at the start and checking the
> time after each loop, but it seems a bit innefficient.
long endTime = System.currentTimeMillis() + 60 * 1000;
while (endTime > System.currentTimeMillis()) {
makeRequest();
}
Whats inefficient about that? It does exactly what you want, and
nothing you don't. It would be a little different if you didn't do
anything in the while loop. Some people mistakenly use that as a
delay/sleep mechanism.
// BAD:
while (endTime > System.currentTimeMillis()) { /* do nothing */}
Hope this helps.
Daniel.
Red Orchid - 02 May 2007 17:24 GMT
Daniel Pitts <googlegroupie@coloraura.com> wrote or quoted in
Message-ID <1178116602.911032.319830@y5g2000hsa.googlegroups.com>:
> long endTime = System.currentTimeMillis() + 60 * 1000;
> while (endTime > System.currentTimeMillis()) {
> makeRequest();
> }
I think that the following code is only proper for simple testing.
<code>
long startTime = System.currentTimeMillis();
... // code block #1
long endTime = System.currentTimeMillis();
long interval = endTime - startTime;
</code>
"interval" is unreliable value because "System.currentTimeMillis()"
returns current time of *system*. In other words, if system time
is set to 01/01/1970 during "#1", the value of "interval" is negative.
Modern clock programs have the function of automatic synchronization
with internet time server (e.g. clock on WinXP tray).
Daniel Pitts - 03 May 2007 02:49 GMT
> Daniel Pitts <googlegrou...@coloraura.com> wrote or quoted in
> Message-ID <1178116602.911032.319...@y5g2000hsa.googlegroups.com>:
[quoted text clipped - 21 lines]
> Modern clock programs have the function of automatic synchronization
> with internet time server (e.g. clock on WinXP tray).
How about System.nanoTime() then? That has a guaranty on the
difference between two calls, does it not?