How to implement a relative timer in a game?

I want to implement a timer for a game java?

  • 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?

  • Answer:

    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!"); } }

user570098 at Stack Overflow Visit the source

Was this solution helpful to you?

Other answers

java.util.Timer is not a bad choice, but http://download.oracle.com/javase/6/docs/api/javax/swing/Timer.html may be more convenient, as seen in this http://stackoverflow.com/questions/4373625.

trashgod

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 ReminderTask 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 ReminderBeep(30); System.out.println("Task scheduled."); } } Many helpful links out there. http://stackoverflow.com/questions/2427626/java-timer-for-game http://stackoverflow.com/questions/3192698/how-to-solve-this-timer-issue-in-java http://www.cokeandcode.com/info/tut2d-2.html

roadRunner

Use Timer and TimerTask Classes (java.util package).

AVD

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.