简体   繁体   中英

Java util Timer not working correctly

I was wondering if someone might be able to see what I had done wrong here. I am trying to create a timer which will increment the count variable by 1 every second and print it out on the console. However, it prints the first number and then stops and I am not sure what is going on.

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


public class TimerTest  {

    private Timer timer;
    public int count = 0;

    public TimerTest() {
        timer = new Timer();
        timer.schedule(new TimerListener(), 1000);
    }

    private class TimerListener extends TimerTask {

        @Override
        public void run() {
            count++;
            System.out.println(count);
        }

    }

    public static void main(String[] args) {
       new TimerTest();
    }
}

I did find some other questions like this but none of their solutions made any difference to the result.

Thanks.

Your scheduling only runs the task once. You need to add a parameter to use the method schedule(TimerTask task, long delay, long period) :

timer.schedule(new TimerListener(), 1000, 1000);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM