javatimertimertask

How to use Java.Util.Timer


I want to make a simple program that counts seconds up until 100 using Java.Util.Timer The code below is the code I am using, however it simply prints all the numbers out at once without waiting a second between each one. How would I fix that? (Ordinarily I would use a thread.sleep but this is just proof of concept.)

import java.util.Timer;
import java.util.TimerTask;

public class Main {
    static Timer timer = new Timer();
    static int seconds = 0;

    public static void main(String[] agrs) {

        MyTimer();

    }

    public static void MyTimer() {

        TimerTask task;

        task = new TimerTask() {
            @Override
            public void run() { 
                while (seconds < 100) {
                    System.out.println("Seconds = " + seconds);
                    seconds++;
                }
            }
        };
         timer.schedule(task, 0, 1000);

    }

}}

Solution

  • Don't use this while loop:

        task = new TimerTask() {
            @Override
            public void run() { 
                while (seconds < 100) {
                    System.out.println("Seconds = " + seconds);
                    seconds++;
                }
            }
        };
    

    The while loop will run immediately as there's no delay inside of it. Instead you want to Timer itself to be your loop, meaning there's no need for this loop.

    Instead use an if block to check if the count is < some max number and if so, print it out and increment the count.

        task = new TimerTask() {
            private final int MAX_SECONDS = 100;
    
            @Override
            public void run() { 
                if (seconds < MAX_SECONDS) {
                    System.out.println("Seconds = " + seconds);
                    seconds++;
                } else {
                    // stop the timer
                    cancel();
                }
            }
        };