-2

The do while loop will execute for a 30 sec duration.With in that I have to print the current date in every 5 sec... For that I have written a code as below. But it is not working as expected...

public static void main(String[] args) {

    long startTime = System.currentTimeMillis();    
    long duration = (30 * 1000);
    do {        
        while (true) {          
            try {
                System.out.println(" Date: " + new Date());
                Thread.sleep(2 * 1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }


    } while ((System.currentTimeMillis() - startTime) < duration);

}
Hulk
  • 5,295
  • 1
  • 25
  • 49
divz
  • 7,257
  • 22
  • 51
  • 73
  • 3
    I don't see a condition to break out of the inner `while (true)` loop – Kartik Feb 11 '19 at 04:59
  • How do you think the execution of the inner loop should end? Why do you sleep 2 seconds in the inner loop if you want to print something every 5 seconds? – Hulk Feb 11 '19 at 05:00
  • @divz I don't see what are you trying to achieve here. – Divanshu Feb 11 '19 at 05:01
  • Possible duplicate of: https://stackoverflow.com/questions/4544197/how-do-i-schedule-a-task-to-run-at-periodic-intervals – Hulk Feb 11 '19 at 05:47

3 Answers3

2

Other answers demonstrated doing this using while loop and Timer; here is how you can do it using ScheduledExecutorService:

private final static int PERIOD = 5;
private final static int TOTAL = 30;

...

ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.scheduleAtFixedRate(() -> {
    System.out.println(new LocalDate());
}, PERIOD, PERIOD, TimeUnit.SECONDS);
executor.schedule(executor::shutdownNow, TOTAL, TimeUnit.SECONDS);
Kartik
  • 7,194
  • 3
  • 23
  • 43
1

Infinite loop while(true) is causing the trouble for you.

You do not need a do-while loop for this, unless it is a specific requirement.

public static void main(String[] args) throws InterruptedException {
    long startTime = System.currentTimeMillis();
    long duration = (30 * 1000);

    while ((System.currentTimeMillis() - startTime) < duration) {
        System.out.println(" Date: " + new Date());
        Thread.sleep(5000);
    }
}

For do-while loop, you can just refactor as below:

public static void main(String[] args) throws InterruptedException {
    long startTime = System.currentTimeMillis();
    long duration = (30 * 1000);

    do {
        System.out.println(" Date: " + new Date());
        Thread.sleep(5000);
    } while ((System.currentTimeMillis() - startTime) < duration);
}
  • My real requirement is in the do while loop i have to get some server response for 30 seconds.....in between that time every 5 sec i have to send some key press...How i can perform this using the above code? – divz Feb 11 '19 at 05:20
  • In that case, ```Thread.sleep();``` could be tricky. You can use ```java.util.Timer``` as suggested by @elliott-frisch or ```java.util.concurrent.CountDownLatch``` with ```await()``` – Ashutosh Vaidya Feb 11 '19 at 05:24
  • but where i can put the code for getting server response? – divz Feb 11 '19 at 06:01
1

I would use a java.util.Timer; create an anonymous TimerTask to display the Date 6 times on a five second period and then cancel() itself. That could look something like

java.util.Timer t = new java.util.Timer();
java.util.TimerTask task = new java.util.TimerTask() {
    private int count = 0;

    @Override
    public void run() {
        if (count < 6) {
            System.out.println(new Date());
        } else {
            t.cancel();
        }
        count++;
    }
};
t.schedule(task, 0, TimeUnit.SECONDS.toMillis(5));
Elliott Frisch
  • 183,598
  • 16
  • 131
  • 226
  • My real requirement is in the do while loop i have to get some server response for 30 seconds.....in between that time every 5 sec i have to send some key press...How i can perform this using the above code?i tried but bit confused where to put the "get server response code" – divz Feb 11 '19 at 06:08