Created
May 13, 2018 11:07
-
-
Save MrMaurice211/d9d87422eeb4258bfd16ee33dc8d296e to your computer and use it in GitHub Desktop.
Micro Cooldown Class
This file contains 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
import java.util.*; | |
import java.util.concurrent.TimeUnit; | |
import java.util.function.Predicate; | |
import java.util.function.Supplier; | |
public class Cooldown { | |
private static List<Cooldown> cooldowns = new ArrayList<>(); | |
public static Map<UUID, Cooldown> perPlayerCooldown = new HashMap<>(); | |
private long cooldown; | |
private long startingTime; | |
private Supplier<Long> currentTime = () -> System.currentTimeMillis(); | |
public Cooldown(int time, TimeUnit timeUnit) { | |
this.cooldown = timeUnit.toMillis(time); | |
this.startingTime = System.currentTimeMillis(); | |
cooldowns.add(this); | |
} | |
public Cooldown(int time, TimeUnit timeUnit, Runnable startExecution) { | |
this(time, timeUnit); | |
if (startExecution != null) | |
startExecution.run(); | |
} | |
public Predicate<Long> busy() { | |
return t -> currentTime.get() < startingTime + t; | |
} | |
public void ifFinished(Runnable execute) { | |
if (isFinished()) { | |
cancel(); | |
if (execute != null) | |
execute.run(); | |
} | |
} | |
private boolean isFinished() { | |
return currentTime.get() > startingTime + cooldown; | |
} | |
public long getCooldownTime(TimeUnit as) { | |
return as.convert(cooldown, TimeUnit.MILLISECONDS); | |
} | |
public long getStartTime() { | |
return startingTime; | |
} | |
public Supplier<Long> getCurrentTime() { | |
return () -> currentTime.get() - startingTime + cooldown; | |
} | |
public void cancel() { | |
cooldowns.remove(this); | |
} | |
public static List<Cooldown> getRunningCooldowns() { | |
return cooldowns; | |
} | |
public static void cancelAllCooldowns() { | |
cooldowns.forEach(cooldowns::remove); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment