Created
November 27, 2015 19:30
-
-
Save YannickFricke/65930ed13a717dd5e79a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class CountDown implements Runnable | |
{ | |
private JavaPlugin plugin; | |
private int countdown = 0; | |
private int threadId = 0; | |
private final Map<Integer, List<CountdownCallback>> callbacks = new HashMap<>(); | |
public CountDown(JavaPlugin plugin, int countdown) | |
{ | |
this.plugin = plugin; | |
this.countdown = countdown; | |
} | |
/** | |
* When an object implementing interface <code>Runnable</code> is used | |
* to create a thread, starting the thread causes the object's | |
* <code>run</code> method to be called in that separately executing | |
* thread. | |
* <p/> | |
* The general contract of the method <code>run</code> is that it may | |
* take any action whatsoever. | |
* | |
* @see Thread#run() | |
*/ | |
@Override | |
public void run() | |
{ | |
if (this.threadId == 0 || this.threadId == -1) | |
{ | |
return; | |
} | |
if (this.callbacks.containsKey(countdown)) | |
{ | |
for (CountdownCallback countdownCallback : this.callbacks.get(this.countdown)) | |
{ | |
countdownCallback.onTick(this.countdown); | |
} | |
} | |
this.countdown--; | |
if (this.countdown == -1) | |
{ | |
Bukkit.getScheduler().cancelTask(this.threadId); | |
} | |
} | |
public void start() throws Exception | |
{ | |
this.threadId = Bukkit.getScheduler().scheduleSyncRepeatingTask(this.plugin, this, 0, 20); | |
if (this.threadId == -1) | |
{ | |
Exception exception = new Exception("Can't start thread"); | |
StackTraceElement stackTraceElement = new StackTraceElement("CountDown.class", "start", "CountDown.java", 61); | |
StackTraceElement[] stackTraceElements = new StackTraceElement[1]; | |
stackTraceElements[0] = stackTraceElement; | |
exception.setStackTrace(stackTraceElements); | |
throw exception; | |
} | |
} | |
public void addCallback(int seconds, CountdownCallback countdownCallback) | |
{ | |
if (!this.callbacks.containsKey(seconds)) | |
{ | |
this.callbacks.put(seconds, new ArrayList<CountdownCallback>()); | |
} | |
this.callbacks.get(seconds).add(countdownCallback); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public interface CountdownCallback | |
{ | |
void onTick(int secondsRemaining); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment