Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// Coundown class by @CeramicTitan / @ZeusAllMighty11, modified by GameplayJDK
package de.GameplayJDK.Lib.Util.Runnables;
import org.bukkit.plugin.Plugin;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scheduler.BukkitTask;
public class Countdown {
// ==================================================================== \\
public interface CountdownHandler {
public void onStart();
public void onFinish();
public void onTick(int tick);
}
// ==================================================================== \\
Plugin plugin; // the main class which extends JavaPlugin
int time; // how long the countdown will run for(In Seconds).
BukkitTask task; // task variable
CountdownHandler handler; // handler interface implemented
boolean finished; // if the countdown is finished
// ==================================================================== \\
/**
* @param plugin - Replace Goblet with the name of your class that extends JavaPlugin
* @param length - How long the plugin will run for
*/
public Countdown(Plugin plugin, int length)
{
this.plugin = plugin;
this.time = length;
}
// ==================================================================== \\
public void start() {
// lets all implementing interfaces know it started
handler.onStart();
// schedule runnable
task = new BukkitRunnable() {
@Override
public void run() {
if(time <1) {
finished = true;
handler.onFinish();
task.cancel();
return;
}
handler.onTick(time); // give the current time (in Seconds) to the onTick method to allow operations depending on time
time--;
}
}.runTaskTimer(plugin, 0L, 20L);// Start without delay (0L), Repeat every 20 ticks (ca. 1s)
// This method depends on how many tps the server has, which may differ.
// The more exact method is to use runTaskTimerAsychronously (which is executed in an seperate thread) instead of runTaskTimer (which is executed by the main server thread like everything else)
}
public void stop() {
task.cancel();
}
public boolean isFinished() {
return finished;
}
// ==================================================================== \\
/*
*
* When you declare your countdown variable, use the setHandler method
* so your plugin can "listen" to the onStart, onTick, and onFinish "events"
*
*/
public void setHandler(CountdownHandler handler) {
this.handler=handler;
}
// ==================================================================== \\
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment