Yoav Levavi
Yoav Levavi

Reputation: 85

How to add loop timer in Java?

How to loop this timer? I want to print every 1 second.

Timer timer = new Timer();
timer = new Timer(false);
for (int i = 0; i < 10; i++) {
   timer.schedule(new TimerTask() {
      @Override
      public void run() {
         i--;
         System.out.println("Java " + i);
      }
   }, 0, 1000);
}

Upvotes: 1

Views: 4904

Answers (2)

libik
libik

Reputation: 23029

Good way is to create your own TimerTask class.

In your Main class, you have this main method :

   public static void main(String[] args) {
        Timer timer = new Timer();
        timer.schedule(new MyTimerTask(10), 1000, 1000);
    }

And then you only need create your own TimerTask class

import java.util.TimerTask;

public class MyTimerTask extends TimerTask {
    private int i2;
    public MyTimerTask(int i2){
        this.i2 = i2;
    }
    @Override
    public void run() {
        System.out.println("heej: " + i2);
    }    
}

This is outputing heej: 10 every second.


With your own class, you can control what is happeing there like this :

import java.util.TimerTask;

public class MyTimerTask extends TimerTask {
    private int i2;
    private int count = 0;

    public MyTimerTask(int i2){
        this.i2 = i2;
    }
    @Override
    public void run() {
        count++;
        System.out.println("heej: " + i2);
        if (count > 10){
            this.cancel();            
        }
    }    
}

Upvotes: 0

Marco Acierno
Marco Acierno

Reputation: 14847

If it's really what you want, change

}, 0, 1000);

to

}, 0, i * 1000);

And put i = 0 to i = 1, and 11 not 10 or use <=

It will create and schedule a new TimerTask 10 times

Upvotes: 2

Related Questions