Andreas Mohrhard
Andreas Mohrhard

Reputation: 197

Games in Java: Timing with possibility of pause/resume

currently i am developing a set of simple games for Java (with JavaFX2 as GUI). Just now i ran into the need of "pausable timers". Does anybody know a library for game timing that enables me to pause timers without implementing it myself? For implementing countdowns and fixed rate things.

I need to: - schedule TimerTasks at a specific rate (thats already in the JDK) - schedule TimerTasks with a fixed delay - pause the timer - resume the timers so that everything starts of where i paused it.

It would be really cool if somebody knew something like that.

Thanks.

Upvotes: 0

Views: 510

Answers (2)

Pushkar
Pushkar

Reputation: 7580

You may want to take a a look at Quartz Standby method -

http://www.quartz-scheduler.org/docs/api/1.8.1/org/quartz/Scheduler.html#standby()

From the API -

Temporarily halts the Scheduler's firing of Triggers.

When start() is called (to bring the scheduler out of stand-by mode), trigger misfire instructions will NOT be applied during the execution of the start() method - any misfires will be detected immediately afterward (by the JobStore's normal process).

The scheduler is not destroyed, and can be re-started at any time.

Quartz is a very good framework which you can plugin to your application. It is also highly customizable so you can utilize it.

Upvotes: 0

Joe K
Joe K

Reputation: 18434

I'm pretty certain there's nothing in the JDK that does this, and I don't know of any libraries to do it.

However, I think instead of trying to pause and resume some sort of timer, you should simply wrap anything that relies on executing periodically in a condition so that it only executes when not paused. If the rate at which tasks are scheduled is sufficiently fast, the difference should not be noticeable for the user. For example:

public abstract class PausableTask extends TimerTask {
  private final AtomicBoolean isPaused;

  public PausableTask(AtomicBoolean flag) {
    isPaused = flag;
  }

  @Override public final void run() {
    if (!isPaused.get()) go();
  }

  public abstract void go();
}

Then you could have one global paused flag, and any time you are using TimerTasks, use this class instead, passing the global flag. You could even make the flag a public static variable of the PausableTask class.

Maybe this approach isn't even applicable to your game and you have some reason to need more accurate pausing, but if not, hopefully this helps!

Upvotes: 3

Related Questions