4

I want to have a method startTimer(30) where the parameter is the amount of seconds to countdown. How do I do so in Java?

Andrew Thompson
  • 166,747
  • 40
  • 210
  • 420
Technupe
  • 4,513
  • 13
  • 32
  • 37

4 Answers4

4

java.util.Timer is not a bad choice, but javax.swing.Timer may be more convenient, as seen in this example.

Community
  • 1
  • 1
trashgod
  • 200,320
  • 28
  • 229
  • 974
  • Unless this is a game played from the command line (do people still *make* those?) a Swing `Timer` would seem an obvious choice. – Andrew Thompson Apr 19 '11 at 02:58
3

The Java 5 way of doing this would be something like:

void startTimer(int delaySeconds) {
  Executors.newSingleThreadScheduledExecutor().schedule(
    runnable,
    delaySeconds,
    TimeUnit.SECONDS);
}

The runnable describes what you want to do. For example:

Runnable runnable = new Runnable() {
  @Override public void run() {
    System.out.println("Hello, world!");
  }
}
sjr
  • 9,619
  • 1
  • 23
  • 36
2
import java.awt.*;
import java.util.Timer;
import java.util.TimerTask;

public class TimerDemo {
  Toolkit toolkit;

  Timer timer;

  public TimerDemo(int seconds) {
    toolkit = Toolkit.getDefaultToolkit();
    timer = new Timer();
    timer.schedule(new RemindTask(), seconds * 1000);
  }

  class RemindTask extends TimerTask {
    public void run() {
      System.out.println("Time's up!");
      toolkit.beep();
      System.exit(0); 
    }
  }

  public static void main(String args[]) {
    System.out.println("About to schedule task.");
    new TimerDemo(30);
    System.out.println("Task scheduled.");
  }
}  

Many helpful links out there.

Community
  • 1
  • 1
Saurabh Gokhale
  • 51,864
  • 34
  • 134
  • 163
0

Helping presented solution by "Javascript is GOD", I do this, play a game at a specific time.

public static void main(String args[]) {
  boolean flag = true;
  while (flag) {
      new TimerDemo(30);
      game();
    }
}

Notice that the flag variable changes within the game().

ParisaN
  • 1,397
  • 2
  • 18
  • 47