0

I'm making a Software by Java (& Netbeans IDE) and one of the features I would like to add is a timer that can be given a certain time (1 hour) and then let it run backwards till it goes 00:00:00 where it will do a certain action.

I tried to do something with my knowledge of adding a clock to the program but it didn't work. Please help

jmj
  • 237,923
  • 42
  • 401
  • 438
Hashan Wijetunga
  • 181
  • 2
  • 3
  • 9

3 Answers3

4

You could try this:

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

public class CountDown {    
     Timer timer;
     public CountDown() {
        timer = new Timer();
        timer.schedule(new DisplayCountdown(), 0, 1000);
    }
    class DisplayCountdown extends TimerTask {

          int seconds = 60;
          public void run() {
               if (seconds > 0) {
                  System.out.println(seconds + " seconds remaining");
                  seconds--;
               } else {

                  System.out.println("Countdown finished");
                  System.exit(0);
              }    
        }
   }     
   public static void main(String args[]) {

      System.out.println("Countdown Beginning");    
      new CountDown();    
   }    
}

Read more: http://www.ehow.com/how_8675868_countdown-tutorial-java.html#ixzz2guYw8c99

Prabhakaran Ramaswamy
  • 25,706
  • 10
  • 57
  • 64
m.lanser
  • 484
  • 8
  • 25
0

I would start a new Thread where it waits 100 milliseconds (Thread.sleep(1000)) and then subtract that from hours * 60 /or minutes/ * 60 /* or seconds */ * 1000. If the result == 0 then you've hit that time.

APerson
  • 702
  • 6
  • 10
0

Do you need to continuously display the countdown? If so, check this out: Java swing timer not decrementing the right way and not starting at the correct hour

If not, just use javax.Swing.Timer and set it for non-repeat and 3600 * 1000 millis

Edit: if you are not using Swing, then perhaps java.util.Timer

Community
  • 1
  • 1
Irina Rapoport
  • 1,404
  • 1
  • 20
  • 37