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?
java.util.Timer
is not a bad choice, but javax.swing.Timer
may be more convenient, as seen in this example.
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!");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With