Skip to content

Instantly share code, notes, and snippets.

@YannickFricke
Created November 27, 2015 19:30
Show Gist options
  • Save YannickFricke/65930ed13a717dd5e79a to your computer and use it in GitHub Desktop.
Save YannickFricke/65930ed13a717dd5e79a to your computer and use it in GitHub Desktop.
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);
}
}
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