Skip to content

Commit

Permalink
Move all scheduling to Scheduler
Browse files Browse the repository at this point in the history
Clean separation of concerns, de-clutter main plugin class, use improved Durations API
  • Loading branch information
minoneer committed Feb 10, 2025
1 parent d07d584 commit a0404c3
Show file tree
Hide file tree
Showing 14 changed files with 120 additions and 132 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import com.google.inject.Inject;
import com.google.inject.Singleton;
import dk.lockfuglsang.minecraft.po.I18nUtil;
import dk.lockfuglsang.minecraft.util.TimeUtil;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
Expand All @@ -19,7 +18,9 @@
import us.talabrek.ultimateskyblock.island.IslandInfo;
import us.talabrek.ultimateskyblock.player.PlayerInfo;
import us.talabrek.ultimateskyblock.uSkyBlock;
import us.talabrek.ultimateskyblock.util.Scheduler;

import java.time.Duration;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
Expand All @@ -37,10 +38,12 @@ public class InviteHandler implements Listener {
private final Map<UUID, Invite> inviteMap = new HashMap<>();
private final Map<String, Map<UUID, String>> waitingInvites = new HashMap<>();
private final uSkyBlock plugin;
private final Scheduler scheduler;

@Inject
public InviteHandler(@NotNull uSkyBlock plugin) {
public InviteHandler(@NotNull uSkyBlock plugin, @NotNull Scheduler scheduler) {
this.plugin = plugin;
this.scheduler = scheduler;
}

private synchronized void invite(Player player, final IslandInfo island, Player otherPlayer) {
Expand Down Expand Up @@ -73,8 +76,8 @@ private synchronized void invite(Player player, final IslandInfo island, Player
tr("\u00a7f/island [accept/reject]\u00a7e to accept or reject the invite."),
tr("\u00a74WARNING: You will lose your current island if you accept!")
});
long timeout = TimeUtil.secondsAsMillis(plugin.getConfig().getInt("options.party.invite-timeout", 30));
BukkitTask timeoutTask = plugin.async(() -> uninvite(island, uniqueId), timeout);
Duration timeout = Duration.ofSeconds(plugin.getConfig().getInt("options.party.invite-timeout", 30));
BukkitTask timeoutTask = scheduler.async(() -> uninvite(island, uniqueId), timeout);
invite.setTimeoutTask(timeoutTask);
island.sendMessageToIslandGroup(true, I18nUtil.marktr("{0}\u00a7d invited {1}"), player.getDisplayName(), otherPlayer.getDisplayName());
}
Expand Down Expand Up @@ -212,6 +215,7 @@ public void onRejectEvent(RejectEvent e) {
}
}

// TODO: cleanup
@SuppressWarnings("UnusedDeclaration")
private static class Invite {
private final long time;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,19 +12,22 @@
import us.talabrek.ultimateskyblock.player.PatienceTester;
import us.talabrek.ultimateskyblock.player.PlayerInfo;
import us.talabrek.ultimateskyblock.uSkyBlock;
import us.talabrek.ultimateskyblock.util.LogUtil;

import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import static dk.lockfuglsang.minecraft.po.I18nUtil.marktr;
import static dk.lockfuglsang.minecraft.po.I18nUtil.tr;

public class InfoCommand extends RequireIslandCommand {

private final Logger logger;

@Inject
public InfoCommand(@NotNull uSkyBlock plugin) {
public InfoCommand(@NotNull uSkyBlock plugin, @NotNull Logger logger) {
super(plugin, "info", "usb.island.info", "?island", marktr("check your or another''s island info"));
this.logger = logger;
addFeaturePermission("usb.island.info.other", tr("allows user to see others island info"));
}

Expand Down Expand Up @@ -96,14 +99,12 @@ public void run() {
PatienceTester.stopRunning(player, "usb.island.info.active");
}
};
plugin.sync(() -> {
try {
PatienceTester.startRunning(player, "usb.island.info.active");
plugin.calculateScoreAsync(player, playerInfo.locationForParty(), showInfo);
} catch (Exception e) {
LogUtil.log(Level.SEVERE, "Error while calculating Island Level", e);
}
}, 1L);
try {
PatienceTester.startRunning(player, "usb.island.info.active");
plugin.calculateScoreAsync(player, playerInfo.locationForParty(), showInfo);
} catch (Exception e) {
logger.log(Level.SEVERE, "Error while calculating Island Level", e);
}
return true;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ public EditSession createEditSession(World world, int maxBlocks) {

@Override
public void regenerate(final Region region, final Runnable onCompletion) {
uSkyBlock.getInstance().sync(() -> {
uSkyBlock.getInstance().getScheduler().sync(() -> {
try (EditSession editSession = WorldEditHandler.createEditSession(region.getWorld(), (int) region.getVolume())) {
editSession.setReorderMode(EditSession.ReorderMode.MULTI_STAGE);
editSession.setSideEffectApplier(SideEffectSet.defaults());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,30 +7,35 @@
import us.talabrek.ultimateskyblock.PluginConfig;
import us.talabrek.ultimateskyblock.island.task.RecalculateRunnable;
import us.talabrek.ultimateskyblock.uSkyBlock;
import us.talabrek.ultimateskyblock.util.Scheduler;

import java.time.Duration;

import static dk.lockfuglsang.minecraft.util.TimeUtil.durationAsTicks;

@Singleton
public class AutoIslandLevelRefresh {

private final uSkyBlock plugin;
private final PluginConfig config;
private final Scheduler scheduler;

private BukkitTask autoRecalculateTask = null;

@Inject
public AutoIslandLevelRefresh(@NotNull uSkyBlock plugin, @NotNull PluginConfig config) {
public AutoIslandLevelRefresh(
@NotNull uSkyBlock plugin,
@NotNull PluginConfig config,
@NotNull Scheduler scheduler
) {
this.plugin = plugin;
this.config = config;
this.scheduler = scheduler;
}

public void startup() {
int refreshEveryMinute = config.getYamlConfig().getInt("options.island.autoRefreshScore", 0);
if (refreshEveryMinute > 0) {
long refreshTicks = durationAsTicks(Duration.ofMinutes(refreshEveryMinute));
autoRecalculateTask = new RecalculateRunnable(plugin).runTaskTimer(plugin, refreshTicks, refreshTicks);
Duration refreshRate = Duration.ofMinutes(refreshEveryMinute);
autoRecalculateTask = scheduler.sync(new RecalculateRunnable(plugin), refreshRate, refreshRate);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@
import us.talabrek.ultimateskyblock.player.PlayerInfo;
import us.talabrek.ultimateskyblock.player.PlayerPerk;
import us.talabrek.ultimateskyblock.uSkyBlock;
import us.talabrek.ultimateskyblock.util.Scheduler;

import java.time.Duration;

import static dk.lockfuglsang.minecraft.po.I18nUtil.tr;

Expand All @@ -19,6 +22,7 @@
*/
public class GenerateTask extends BukkitRunnable {
private final uSkyBlock plugin;
private final Scheduler scheduler;
private final Player player;
private final PlayerInfo pi;
private final Location next;
Expand All @@ -29,6 +33,7 @@ public class GenerateTask extends BukkitRunnable {

public GenerateTask(uSkyBlock plugin, final Player player, final PlayerInfo pi, final Location next, PlayerPerk playerPerk, String schematicName) {
this.plugin = plugin;
this.scheduler = plugin.getScheduler();
this.player = player;
this.pi = pi;
this.next = next;
Expand Down Expand Up @@ -59,33 +64,30 @@ public void run() {
WorldGuardHandler.updateRegion(islandInfo);
plugin.getCooldownHandler().resetCooldown(player, "restart", Settings.general_cooldownRestart);

plugin.sync(new Runnable() {
@Override
public void run() {
if (pi != null) {
pi.setIslandGenerating(false);
}
plugin.clearPlayerInventory(player);
if (player != null && player.isOnline()) {
if (plugin.getConfig().getBoolean("options.restart.teleportWhenReady", true)) {
player.sendMessage(tr("\u00a7aCongratulations! \u00a7eYour island has appeared."));
if (AsyncWorldEditHandler.isAWE()) {
player.sendMessage(tr("\u00a7cNote:\u00a7e Construction might still be ongoing."));
}
plugin.getTeleportLogic().homeTeleport(player, true);
} else {
player.sendMessage(new String[]{
tr("\u00a7aCongratulations! \u00a7eYour island has appeared."),
tr("Use \u00a79/is h\u00a7r or the \u00a79/is\u00a7r menu to go there."),
tr("\u00a7cNote:\u00a7e Construction might still be ongoing.")});
}
}
for (String command : plugin.getConfig().getStringList("options.restart.extra-commands")) {
plugin.execCommand(player, command, true);
scheduler.sync(() -> {
if (pi != null) {
pi.setIslandGenerating(false);
}
plugin.clearPlayerInventory(player);
if (player != null && player.isOnline()) {
if (plugin.getConfig().getBoolean("options.restart.teleportWhenReady", true)) {
player.sendMessage(tr("\u00a7aCongratulations! \u00a7eYour island has appeared."));
if (AsyncWorldEditHandler.isAWE()) {
player.sendMessage(tr("\u00a7cNote:\u00a7e Construction might still be ongoing."));
}
plugin.getTeleportLogic().homeTeleport(player, true);
} else {
player.sendMessage(
tr("\u00a7aCongratulations! \u00a7eYour island has appeared."),
tr("Use \u00a79/is h\u00a7r or the \u00a79/is\u00a7r menu to go there."),
tr("\u00a7cNote:\u00a7e Construction might still be ongoing.")
);
}
}, plugin.getConfig().getInt("options.restart.teleportDelay", 2000)
}
for (String command : plugin.getConfig().getStringList("options.restart.extra-commands")) {
plugin.execCommand(player, command, true);
}
}, Duration.ofMillis(plugin.getConfig().getInt("options.restart.teleportDelay", 2000))
);
}
}

Original file line number Diff line number Diff line change
@@ -1,27 +1,28 @@
package us.talabrek.ultimateskyblock.island.task;

import dk.lockfuglsang.minecraft.po.I18nUtil;
import dk.lockfuglsang.minecraft.util.TimeUtil;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
import us.talabrek.ultimateskyblock.uSkyBlock;
import us.talabrek.ultimateskyblock.util.LocationUtil;
import dk.lockfuglsang.minecraft.util.TimeUtil;
import us.talabrek.ultimateskyblock.util.Scheduler;

/**
* A task that looks for a chest at an island location.
*/
public class LocateChestTask extends BukkitRunnable {
private final uSkyBlock plugin;
private final Player player;
private final Location islandLocation;
private final GenerateTask onCompletion;
private final Scheduler scheduler;
private final long timeout;

private long tStart;

public LocateChestTask(uSkyBlock plugin, Player player, Location islandLocation, GenerateTask onCompletion) {
this.plugin = plugin;
this.scheduler = plugin.getScheduler();
this.player = player;
this.islandLocation = islandLocation;
this.onCompletion = onCompletion;
Expand All @@ -40,11 +41,11 @@ public void run() {
} else {
cancel();
if (chestLocation == null && player != null && player.isOnline()) {
player.sendMessage(I18nUtil.tr("\u00a7cWatchdog!\u00a79 Unable to locate a chest within {0}, bailing out.", TimeUtil.millisAsString(timeout-tStart)));
player.sendMessage(I18nUtil.tr("\u00a7cWatchdog!\u00a79 Unable to locate a chest within {0}, bailing out.", TimeUtil.millisAsString(timeout - tStart)));
}
if (onCompletion != null) {
onCompletion.setChestLocation(chestLocation);
plugin.sync(onCompletion);
scheduler.sync(onCompletion);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public void run() {
}
}
if (!recalcIslands.isEmpty()) {
RecalculateTopTen runnable = new RecalculateTopTen(plugin, recalcIslands);
RecalculateTopTen runnable = new RecalculateTopTen(plugin, plugin.getScheduler(), recalcIslands);
runnable.runTaskAsynchronously(plugin);
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,34 +1,35 @@
package us.talabrek.ultimateskyblock.island.task;

import org.bukkit.scheduler.BukkitRunnable;
import us.talabrek.ultimateskyblock.api.event.uSkyBlockEvent;
import us.talabrek.ultimateskyblock.api.async.Callback;
import us.talabrek.ultimateskyblock.api.event.uSkyBlockEvent;
import us.talabrek.ultimateskyblock.uSkyBlock;
import us.talabrek.ultimateskyblock.util.Scheduler;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.Collection;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
*/
public class RecalculateTopTen extends BukkitRunnable {
private final List<String> locations;
private final Queue<String> locations;
private final uSkyBlock plugin;
private final Scheduler scheduler;

public RecalculateTopTen(uSkyBlock plugin, Set<String> locations) {
public RecalculateTopTen(uSkyBlock plugin, Scheduler scheduler, Collection<String> locations) {
this.locations = new ConcurrentLinkedQueue<>(locations);
this.plugin = plugin;
this.locations = new ArrayList<>(locations);
this.scheduler = scheduler;
}

@Override
public void run() {
if (!locations.isEmpty()) {
String islandName = locations.remove(0);
String islandName = locations.poll();
if (islandName != null) {
plugin.calculateScoreAsync(null, islandName, new Callback<>() {
@Override
public void run() {
// We use the deprecated on purpose (the other would fail).
plugin.async(RecalculateTopTen.this);
scheduler.async(RecalculateTopTen.this);
}
});
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import org.bukkit.event.inventory.InventoryClickEvent;
import org.jetbrains.annotations.NotNull;
import us.talabrek.ultimateskyblock.uSkyBlock;
import us.talabrek.ultimateskyblock.util.Scheduler;

import java.util.ArrayList;
import java.util.List;
Expand All @@ -25,12 +26,13 @@ public class ConfigMenu {
@Inject
public ConfigMenu(
@NotNull uSkyBlock plugin,
@NotNull MenuItemFactory factory
@NotNull MenuItemFactory factory,
@NotNull Scheduler scheduler
) {
FileConfiguration menuConfig = new YamlConfiguration();
FileUtil.readConfig(menuConfig, getClass().getClassLoader().getResourceAsStream("configmenu.yml"));
this.editMenus = new ArrayList<>();
this.mainMenu = new MainConfigMenu(plugin, menuConfig, factory, editMenus);
this.mainMenu = new MainConfigMenu(plugin, menuConfig, factory, scheduler, editMenus);
this.editMenus.addAll(List.of(
new IntegerEditMenu(menuConfig, factory, mainMenu),
new BooleanEditMenu(menuConfig),
Expand Down
Loading

0 comments on commit a0404c3

Please sign in to comment.