Timestamp, timers, a matter of time

I was Google's timestamps, timers, and something related to time and Java. I just can't get anything to work for me.

I need a timestamp to control the while loop, like the pseudo code below

while(true)
{

    while(mytimer.millsecounds < amountOftimeIwantLoopToRunFor)
    { 
        dostuff();
    }

    mytimer.rest();  

}

Any ideas what data type I could use; I tried Timestamp but didn't seem to work.

Thanks Ciarán

+3
source share
1 answer

Do something like:

long maxduration = 10000; // 10 seconds.
long endtime = System.currentTimeMillis() + maxduration;

while (System.currentTimeMillis() < endtime) {
    // ...
}

Alternative (more advanced) uses java.util.concurrent.ExecutorService. Here is SSCCE :

package com.stackoverflow.q2303206;

import java.util.Arrays;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class Test {

    public static void main(String... args) throws Exception {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        executor.invokeAll(Arrays.asList(new Task()), 10, TimeUnit.SECONDS); // Get 10 seconds time.
        executor.shutdown();
    }

}

class Task implements Callable<String> {
    public String call() throws Exception {
        while (true) {
            // ...
        }
        return null;
    }
}
+2
source

Source: https://habr.com/ru/post/1733683/


All Articles