Skip to content

Commit

Permalink
Cache towny time
Browse files Browse the repository at this point in the history
  • Loading branch information
Warriorrrr committed Apr 13, 2022
1 parent 46c2526 commit 5b97f7e
Show file tree
Hide file tree
Showing 7 changed files with 90 additions and 79 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
import me.clip.placeholderapi.expansion.PlaceholderExpansion;
import me.clip.placeholderapi.expansion.Relational;

import java.util.Locale;

/**
* This class will be registered through the register-method in the plugins
* onEnable-method.
Expand Down Expand Up @@ -593,8 +595,10 @@ else if (resident.isMayor())
return resident.hasTown() ? resident.getTownOrNull().getBoard() : "";
case "nation_board": // %townyadvanced_nation_board%
return resident.hasTown() ? (resident.hasNation() ? resident.getNationOrNull().getBoard() : "") : "";
case "time_until_new_day_formatted": // %townyadvanced_time_until_new_day_formatted%
return Translatable.of("msg_time_until_a_new_day").append(TimeMgmt.formatCountdownTime(TownyTimerHandler.townyTime(), player.getPlayer())).forLocale(player.getPlayer());
case "time_until_new_day_formatted": {// %townyadvanced_time_until_new_day_formatted%
Locale locale = Translation.getLocale(player);
return Translatable.of("msg_time_until_a_new_day").append(TimeMgmt.formatCountdownTime(TimeMgmt.townyTime(), locale)).translate(locale);
}
case "time_until_new_day_hours_formatted": // %townyadvanced_time_until_new_day_hours_formatted%
return TimeMgmt.formatCountdownTimeHours(TownyTimerHandler.townyTime(), player.getPlayer());
case "time_until_new_day_minutes_formatted": // %townyadvanced_time_until_new_day_minutes_formatted%
Expand Down
12 changes: 9 additions & 3 deletions src/com/palmergames/bukkit/towny/TownyTimerHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,11 @@
import com.palmergames.bukkit.towny.tasks.HourlyTimerTask;
import com.palmergames.bukkit.towny.tasks.ShortTimerTask;
import com.palmergames.bukkit.util.BukkitTools;
import com.palmergames.util.TimeMgmt;
import com.palmergames.util.TimeTools;

import org.bukkit.Bukkit;
import org.jetbrains.annotations.ApiStatus;


/**
Expand Down Expand Up @@ -219,14 +221,18 @@ public static boolean isDrawSpawnPointsTaskRunning() {
return drawSpawnPointsTask != -1;
}

/**
* @deprecated Deprecated, use {@link TimeMgmt#townyTime()}
*/
@Deprecated
@ApiStatus.ScheduledForRemoval
public static Long townyTime() {
return NewDayScheduler.townyTime();
return TimeMgmt.townyTime();
}

public static Long getTimeUntilNextHourInSeconds() {
long timeSinceLastHourMillis = System.currentTimeMillis() % (1000 * 60 * 60);
long timeSinceLastHourSeconds = timeSinceLastHourMillis / 1000;
long timeUntilNextHourSeconds = (60 * 60) - timeSinceLastHourSeconds;
return timeUntilNextHourSeconds;
return (60 * 60) - timeSinceLastHourSeconds;
}
}
3 changes: 1 addition & 2 deletions src/com/palmergames/bukkit/towny/command/TownyCommand.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
import com.palmergames.bukkit.towny.TownyEconomyHandler;
import com.palmergames.bukkit.towny.TownyMessaging;
import com.palmergames.bukkit.towny.TownySettings;
import com.palmergames.bukkit.towny.TownyTimerHandler;
import com.palmergames.bukkit.towny.TownyUniverse;
import com.palmergames.bukkit.towny.TownyCommandAddonAPI.CommandType;
import com.palmergames.bukkit.towny.TownyUpdateChecker;
Expand Down Expand Up @@ -257,7 +256,7 @@ else if (split.length > 1 && split[1].equalsIgnoreCase("hud"))
if (!permSource.testPermission(sender, PermissionNodes.TOWNY_COMMAND_TOWNY_TIME))
throw new TownyException(Translatable.of("msg_err_command_disable"));

TownyMessaging.sendMsg(sender, Translatable.of("msg_time_until_a_new_day").append(TimeMgmt.formatCountdownTime(TownyTimerHandler.townyTime())));
TownyMessaging.sendMsg(sender, Translatable.of("msg_time_until_a_new_day").append(TimeMgmt.formatCountdownTime(TimeMgmt.townyTime(true))));
break;
}
case "universe": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
import com.palmergames.bukkit.towny.TownyEconomyHandler;
import com.palmergames.bukkit.towny.TownyMessaging;
import com.palmergames.bukkit.towny.TownySettings;
import com.palmergames.bukkit.towny.TownyTimerHandler;
import com.palmergames.bukkit.towny.TownyUniverse;
import com.palmergames.bukkit.towny.command.TownCommand;
import com.palmergames.bukkit.towny.command.TownyCommand;
Expand Down Expand Up @@ -160,7 +159,7 @@ public void onPlayerCreateTown(NewTownEvent event) {
double upkeep = TownySettings.getTownUpkeepCost(town);
if (TownyEconomyHandler.isActive() && TownySettings.isTaxingDaily() && upkeep > 0) {
String cost = TownyEconomyHandler.getFormattedBalance(upkeep);
String time = TimeMgmt.formatCountdownTime(TownyTimerHandler.townyTime());
String time = TimeMgmt.formatCountdownTime(TimeMgmt.townyTime(true));
TownyMessaging.sendTownMessagePrefixed(town, Translatable.of("msg_new_town_advice", cost, time));
}
//TODO: at some point it might be nice to have a written_book given to mayors
Expand Down
7 changes: 7 additions & 0 deletions src/com/palmergames/bukkit/towny/object/Translation.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,11 @@
import com.palmergames.bukkit.util.BukkitTools;
import com.palmergames.bukkit.util.Colors;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;

import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
Expand Down Expand Up @@ -206,6 +209,10 @@ public static Locale getLocale(CommandSender sender) {
return sender instanceof Player ? Translation.toLocale(((Player) sender).getLocale(), false) : defaultLocale;
}

public static Locale getLocale(@NotNull OfflinePlayer offlinePlayer) {
return offlinePlayer.isOnline() ? toLocale(offlinePlayer.getPlayer().getLocale(), false) : defaultLocale;
}

public static Locale getLocale(Resident resident) {
return BukkitTools.isOnline(resident.getName()) ? getLocale(resident.getPlayer()) : defaultLocale;
}
Expand Down
28 changes: 7 additions & 21 deletions src/com/palmergames/bukkit/towny/tasks/NewDayScheduler.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
package com.palmergames.bukkit.towny.tasks;

import java.util.Calendar;
import java.util.TimeZone;

import org.bukkit.Bukkit;

import com.palmergames.bukkit.towny.Towny;
Expand All @@ -11,6 +8,7 @@
import com.palmergames.bukkit.util.BukkitTools;
import com.palmergames.util.TimeMgmt;
import com.palmergames.util.TimeTools;
import org.jetbrains.annotations.ApiStatus;

public class NewDayScheduler extends TownyTimerTask {

Expand All @@ -23,7 +21,7 @@ public NewDayScheduler(Towny plugin) {

@Override
public void run() {
long secondsUntilNextNewDay = townyTime();
long secondsUntilNextNewDay = TimeMgmt.townyTime();
plugin.getLogger().info("Time until a New Day: " + TimeMgmt.formatCountdownTime(secondsUntilNextNewDay));

// If the next new day is less than 2 minutes away, schedule the new day.
Expand Down Expand Up @@ -89,25 +87,13 @@ public static void newDay() {
* Calculates the time in seconds until the next new day event.
* TimeZone specific, including daylight savings.
*
* @deprecated Deprecated, use {@link TimeMgmt#townyTime()}
*
* @return seconds until event
*/
@Deprecated
@ApiStatus.ScheduledForRemoval
public static Long townyTime() {

long secondsInDay = TownySettings.getDayInterval();

// Get Calendar instance
Calendar now = Calendar.getInstance();

// Get current TimeZone
TimeZone timeZone = now.getTimeZone();

// Get current system time in milliseconds
long timeMilli = System.currentTimeMillis();

// Calculate the TimeZone specific offset (including DST)
int timeOffset = timeZone.getOffset(timeMilli)/1000;

return Math.floorMod(secondsInDay + (TownySettings.getNewDayTime() - ((timeMilli/1000) % secondsInDay) - timeOffset), secondsInDay);
return TimeMgmt.townyTime();
}

}
108 changes: 59 additions & 49 deletions src/com/palmergames/util/TimeMgmt.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@

import java.text.NumberFormat;

import com.palmergames.bukkit.towny.TownySettings;
import com.palmergames.bukkit.towny.object.Translatable;
import com.palmergames.bukkit.towny.object.Translation;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Calendar;
import java.util.Locale;
import java.util.TimeZone;

import org.bukkit.entity.Player;

Expand All @@ -18,77 +20,38 @@ public class TimeMgmt {
public final static double ONE_HOUR_IN_MILLIS = ONE_MINUTE_IN_MILLIS * 60;
public final static double ONE_DAY_IN_MILLIS = ONE_HOUR_IN_MILLIS * 24;

public final static long[][] defaultCountdownDelays = new long[][] {
{ 10, 1 }, // <= 10s, Warn every 1s
{ 30, 5 }, // <= 30s, Warn every 5s
{ 60, 10 }, // <= minute, Warn every 10s
{ 120, 15 }, // <= 2 minutes, Warn every 15s
{ 5 * 60, 60 }, // <= 5 minutes, Warn every minute
{ 30 * 60, 5 * 60 }, // <= 30 minutes, Warn every 5 minutes
{ 60 * 60, 10 * 60 }, // <= 60 minutes, Warn every 10 minutes
{ 24 * 60 * 60, 60 * 60 }, // <= day, Warn every hour
{ Integer.MAX_VALUE, 24 * 60 * 60 } // <= max, Warn every day
};

public static List<Long> getCountdownDelays(int start) {

return getCountdownDelays(start, defaultCountdownDelays);
}

public static List<Long> getCountdownDelays(int start, long[][] delays) {

List<Long> out = new ArrayList<>();
for (long[] delay : delays)
if (delay.length != 2)
return null;

Integer lastDelayIndex = null;
long nextWarningAt = Integer.MAX_VALUE;
for (long t = start; t > 0; t--) {
for (int d = 0; d < delays.length; d++) {
if (t <= delays[d][0]) {
if (lastDelayIndex == null || t <= nextWarningAt || d < lastDelayIndex) {
lastDelayIndex = d;
nextWarningAt = t - delays[d][1];
out.add(t);
break;
}
}
}
}

return out;
}
private static long lastTownyTimeCacheUpdate = System.currentTimeMillis();
private static long cachedTownyTime = -1;

public static String formatCountdownTime(long l) {

String out = "";
if (l >= 3600) {
int h = (int) (l / 3600.0);
out = h + Translation.of("msg_hours");
l -= h * 3600;
l -= h * 3600L;
}
if (l >= 60) {
int m = (int) (l / 60.0);
out += (out.length() > 0 ? ", " : "") + m + Translation.of("msg_minutes");
l -= m * 60;
l -= m * 60L;
}
if (out.length() == 0 || l > 0)
out += (out.length() > 0 ? ", " : "") + l + Translation.of("msg_seconds");
return out;
}

public static String formatCountdownTime(Long l, Player player) {
public static String formatCountdownTime(Long l, Locale locale) {
String out = "";
if (l >= 3600) {
int h = (int) (l / 3600.0);
out = h + Translatable.of("msg_hours").forLocale(player);
l -= h * 3600;
l -= h * 3600L;
}
if (l >= 60) {
int m = (int) (l / 60.0);
out += (out.length() > 0 ? ", " : "") + m + Translatable.of("msg_minutes").forLocale(player);
l -= m * 60;
l -= m * 60L;
}
if (out.length() == 0 || l > 0)
out += (out.length() > 0 ? ", " : "") + l + Translatable.of("msg_seconds").forLocale(player);
Expand Down Expand Up @@ -157,4 +120,51 @@ public static String getFormattedTimeValue(double timeMillis) {
return "0" + Translation.of("msg_seconds");
}
}

/**
* Calculates the time in seconds until the next new day event.
* TimeZone specific, including daylight savings.
*
* @return seconds until event
*/
public static long townyTime() {
return townyTime(false);
}

/**
* Calculates the time in seconds until the next new day event.
* TimeZone specific, including daylight savings.
*
* @param cache - Whether to use caching or not.
*
* @return seconds until event
*/
public static long townyTime(boolean cache) {

if (cache && lastTownyTimeCacheUpdate + 1000 > System.currentTimeMillis() && cachedTownyTime != -1)
return cachedTownyTime;

long secondsInDay = TownySettings.getDayInterval();

// Get Calendar instance
Calendar now = Calendar.getInstance();

// Get current TimeZone
TimeZone timeZone = now.getTimeZone();

// Get current system time in milliseconds
long timeMilli = System.currentTimeMillis();

// Calculate the TimeZone specific offset (including DST)
int timeOffset = timeZone.getOffset(timeMilli)/1000;

final long time = Math.floorMod(secondsInDay + (TownySettings.getNewDayTime() - ((timeMilli/1000) % secondsInDay) - timeOffset), secondsInDay);

if (cache) {
cachedTownyTime = time;
lastTownyTimeCacheUpdate = System.currentTimeMillis();
}

return time;
}
}

0 comments on commit 5b97f7e

Please sign in to comment.