4

Scenario:
I am making a clone of a popular card game. There needs to be a period during which people can join the game. Sometimes, the period is too short. Therefore, I want to let people extend the waiting period. For the example numbers, the default 'lobby time' is 45 seconds, and each extension is 15 seconds.

Issue:
I have decided to use Java's Timers. When the 'lobby' starts, a TimerTask is scheduled for 45 seconds from now:

UnoStartTimer.schedule(new UnoStartTask(), 45000);

When someone wants to extend the delay, this is the pseudocode I want to run:

UnoStartTimer.reschedule(UnoStartTimer.getNextScheduledTime() + 15000);

A quick look at the javadoc indicates that such an easy solution, with the Timer class, is not present.

Here's the possibilities I came up with:

  • I should use a different scheduling class (I think I saw something called ScheduledExecutorService in an answer to another question, but it didn't immediately seem like it was the solution to my problem)
  • There is a way to do this with Timer, and I'm blatantly overlooking it
  • There isn't an easy way to do this

So, which one is it?

Community
  • 1
  • 1
Riking
  • 2,389
  • 1
  • 24
  • 36

2 Answers2

0

Look at java.util.Timer. Among other things, I see a cancel() method. I also see a schedule() method that takes a Date object rather than a number of milliseconds.

You could create a Date object which is 45 seconds from now, schedule the timer with that time, and if an extension occurs, cancel it, add 15 seconds to the original Date object and schedule the task with that new time.

Elliott
  • 1,336
  • 1
  • 13
  • 26
0

According to the Timer documentation, in Java 1.5 onwards, you should prefer the ScheduledThreadPoolExecutor instead. (You may like to create this executor using Executors.newSingleThreadScheduledExecutor() for ease of use; it creates something much like a Timer.)

Please refer to this post -> Resettable Java Timer

Community
  • 1
  • 1
qgicup
  • 2,189
  • 1
  • 16
  • 13