Java - TimerTask porting for gaming lobby

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

Question :
I decided to use Java Timers. When the lobby starts, TimerTask is assigned for 45 seconds:

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 javadoc indicates that there is no such simple solution with the Timer class.

Here are the features I came up with:

  • I need to use a different planning class (I think I saw something called ScheduledExecutorService in an answer to another question, but it didn’t immediately seem to be the solution to my problem)
  • There is a way to do this with Timer, and I clearly don't notice it.
  • There is no easy way to do this.

So which one?

+4
source share
2 answers

Take a look at java.util.Timer . Among other things, I see the cancel () method. I also see a schedule () method that takes a Date object, not a few milliseconds.

You can create a Date object, which is 45 seconds, set a timer with this time, and if the extension happens, cancel it, add 15 seconds to the original Date object and schedule a task with this new time.

0
source

According to Timer documentation, starting with Java 1.5, you'd better prefer ScheduledThreadPoolExecutor. (You can create this artist using Executors.newSingleThreadScheduledExecutor () for ease of use, it creates something like a timer.)

Please refer to this post -> Resettable Java Timer

0
source

All Articles