-3
package timerrr;

import java.util.*;

public class Timerrr {

  public static void main(String[] args) {

    Timer timer = new Timer();

    timer.schedule(
        new TimerTask() {
          int i = 0;

          @Override
          public void run() {

            System.out.println("timer is still running");
          }
        },
        1 * 150 * 100,
        1 * 50 * 100);
  }
}
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
Aqil
  • 59
  • 2
  • 6

2 Answers2

0

in your overridden run method increment i and if i = 5 cancel the timer:

timer.schedule(new TimerTask() {
     int i = 0;

     @Override
     public void run() {
        i++;
        if(i==5) {
            this.cancel();
        }
        else {
            //YOUR CODE HERE
        }
     }
 }, startDelay, fixedDelay);
Jessie Lulham
  • 110
  • 12
0

Here should be an easier way to do what you want: Calling the Thread.sleep(); method is, for some reason, one of my favorite things to call. You just have to surround it in a try/catch block like so:

public static void main(String[] args) {
  for (int i = 0; i <= 5; i++) {
    System.out.println("timer is still running");
    try {
      Thread.sleep(5000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
}

You may want to put that it it's own method with it's own thread, so that you can have other things running while this is happening.

Hope this helped :)

Kaelinator
  • 360
  • 3
  • 17