cancel tasks on plugin disable

This commit is contained in:
D3v1s0m 2023-05-17 18:47:01 +05:30
parent 40c31b44aa
commit e3d5ebab8b
No known key found for this signature in database
GPG Key ID: 3B6EC35367B8D82E
5 changed files with 36 additions and 0 deletions

@ -212,6 +212,7 @@ public class ZNpcsPlus extends JavaPlugin implements ZApi {
@Override
public void onDisable() {
if (!enabled) return;
scheduler.cancelAll();
npcRegistry.save();
ZApiProvider.unregister();
Bukkit.getOnlinePlayers().forEach(userManager::remove);

@ -117,6 +117,18 @@ public final class Reflections {
.setStrict(FoliaUtil.isFolia())
.toMethodReflection();
public static final ReflectionLazyLoader<Method> FOLIA_CANCEL_ASYNC_TASKS =
new ReflectionBuilder(ASYNC_SCHEDULER_CLASS)
.withMethodName("cancelTasks")
.setStrict(FoliaUtil.isFolia())
.toMethodReflection();
public static final ReflectionLazyLoader<Method> FOLIA_CANCEL_GLOBAL_TASKS =
new ReflectionBuilder(GLOBAL_REGION_SCHEDULER_CLASS)
.withMethodName("cancelTasks")
.setStrict(FoliaUtil.isFolia())
.toMethodReflection();
public static final ReflectionLazyLoader<Method> FOLIA_TELEPORT_ASYNC =
new ReflectionBuilder(Entity.class)
.withMethodName("teleportAsync")

@ -41,5 +41,21 @@ public class FoliaScheduler extends TaskScheduler {
throw new RuntimeException(e);
}
}
@Override
public void cancelAll() {
try {
Object asyncScheduler = Reflections.FOLIA_GET_ASYNC_SCHEDULER.get().invoke(null);
Reflections.FOLIA_CANCEL_ASYNC_TASKS.get().invoke(asyncScheduler, plugin);
} catch (IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException(e);
}
try {
Object globalScheduler = Reflections.FOLIA_GET_GLOBAL_REGION_SCHEDULER.get().invoke(null);
Reflections.FOLIA_CANCEL_GLOBAL_TASKS.get().invoke(globalScheduler, plugin);
} catch (IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException(e);
}
}
}

@ -22,4 +22,9 @@ public class SpigotScheduler extends TaskScheduler {
public void runDelayedTimerAsync(Runnable runnable, long delay, long ticks) {
Bukkit.getScheduler().runTaskTimerAsynchronously(plugin, runnable, delay, ticks);
}
@Override
public void cancelAll() {
Bukkit.getScheduler().cancelTasks(plugin);
}
}

@ -14,4 +14,6 @@ public abstract class TaskScheduler {
public abstract void runLaterAsync(Runnable runnable, long ticks);
public abstract void runDelayedTimerAsync(Runnable runnable, long delay, long ticks);
public abstract void cancelAll();
}