Reputation: 21
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.
Upvotes: 1
Views: 1400
Reputation: 46209
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);
Upvotes: 5