Created
December 18, 2020 20:39
-
-
Save zkingboos/aba690c14b117de4043d4e1f08e56eba to your computer and use it in GitHub Desktop.
This file contains hidden or 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
package com.github.zkingboos.util; | |
import lombok.NonNull; | |
import org.bukkit.Bukkit; | |
import org.bukkit.plugin.Plugin; | |
public abstract class ReutilizableTask implements Runnable { | |
private int taskId; | |
public ReutilizableTask() { | |
resetTaskId(); | |
} | |
public synchronized void runTaskTimerAsynchronously(@NonNull Plugin plugin, long delay, long period) throws IllegalStateException { | |
checkState(); | |
this.taskId = Bukkit | |
.getScheduler() | |
.runTaskTimerAsynchronously(plugin, this, delay, period) | |
.getTaskId(); | |
} | |
public synchronized void runTask(@NonNull Plugin plugin) throws IllegalStateException { | |
checkState(); | |
this.taskId = Bukkit | |
.getScheduler() | |
.runTask(plugin, this) | |
.getTaskId(); | |
} | |
public synchronized void runTaskAsynchronously(@NonNull Plugin plugin) throws IllegalStateException { | |
checkState(); | |
this.taskId = Bukkit | |
.getScheduler() | |
.runTaskAsynchronously(plugin, this) | |
.getTaskId(); | |
} | |
public synchronized void runTaskLater(@NonNull Plugin plugin, long delay) throws IllegalStateException { | |
checkState(); | |
this.taskId = Bukkit | |
.getScheduler() | |
.runTaskLater(plugin, this, delay) | |
.getTaskId(); | |
} | |
public synchronized void runTaskLaterAsynchronously(@NonNull Plugin plugin, long delay) throws IllegalStateException { | |
checkState(); | |
this.taskId = Bukkit | |
.getScheduler() | |
.runTaskLaterAsynchronously(plugin, this, delay) | |
.getTaskId(); | |
} | |
public synchronized void runTaskTimer(@NonNull Plugin plugin, long delay, long period) throws IllegalStateException { | |
checkState(); | |
this.taskId = Bukkit | |
.getScheduler() | |
.runTaskTimer(plugin, this, delay, period) | |
.getTaskId(); | |
} | |
public synchronized void cancel() { | |
final int taskId = getTaskId(); | |
if (taskId == -1) return; | |
Bukkit.getScheduler().cancelTask(taskId); | |
resetTaskId(); | |
} | |
public synchronized void checkState() throws IllegalStateException { | |
if (getTaskId() != -1) { | |
throw new IllegalStateException("Cant restart an already initialized task"); | |
} | |
} | |
public synchronized void resetTaskId() { | |
this.taskId = -1; | |
} | |
public synchronized int getTaskId() { | |
return taskId; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment