How do I make a countdown from 10 for a Bukkit Plugin?

Viewed 700

I am trying to make a Championships kind of plugin where there is a start-game command that starts the game after counting down from 10. However, I cannot find a way to wait 1 second as an interval in the countdown. I have tried Object.wait(long) and BukkitScheduler.setRepeatingDelayedTask() but neither of them are working out for me (object.wait() returns java.lang.IllegalMonitorStateException: current thread is not owner and BukkitScheduler.setRepeatingDelayedTask() errors in my editor). Anyone know a workaround to this?

2 Answers
// See how many seconds have been counted
private int count;
private BukkitTask task;

public void doStuff() {
    // Reset count
    count = 0;
    task = new BukkitRunnable() {
        @Override
        public void run() {
            // If count is less than or equal to ten, increment count, otherwise set count to -1.
            count = count <= 10 ? count + 1 : -1;
            if (count >= 10 || count == -1) {
                // Cancel task if count is over 10s
                task.cancel();
                return;
            }
            Bukkit.getLogger().log(Level.INFO, "Seconds passed: " + count + "!";
        }
    }.runTaskTimer(YourPlugin.getPlugin(), 0, 20);
}

Use BukkitScheduler is the solution. But, it count in tick where 20 ticks = 1 seconds.

So, you have to do something like this:

private BukkitTask task;
private int count;

public void startTimer() {
   count = 10; // restart count down at 10 seconds
   task = Bukkit.getScheduler().runTaskTimer(MyPlugin.getInstance(), ()-> {
      // here what you want
      if(count == 0)
         task.cancel(); // cancel the task if the counter is finished
      count--; // reduce the counter
   }, 20, 20);
}

The first "20" is the time before starting scheduler. The second is the time between each call (both in ticks).

Also, don't use Thread.sleep() or Object.wait() because they could freeze the full server, and maybe timed out everyone...

Related