works:programmer:java:flood-protected-method-class
Класс защищающий конечный метод от флуда
- FloodProtectedMethod.java
import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; import java.util.Objects; public class FloodProtectedMethod { private LocalDateTime shallExecutedAfter = null; private ChronoUnit chronoUnit; private long delay; public FloodProtectedMethod(ChronoUnit chronoUnit, long delay) { this.chronoUnit = chronoUnit; this.delay = delay; } public boolean inject(Runnable runnable) { LocalDateTime now = LocalDateTime.now(); synchronized(this) { if (Objects.isNull(shallExecutedAfter) || shallExecutedAfter.isBefore(now)) { shallExecutedAfter = now.plus(delay, chronoUnit); runnable.run(); return true; } } return false; } }
private final FloodProtectedMethod healProtect = new FloodProtectedMethod(ChronoUnit.SECONDS, 30); void doHeal() { healProtect.inject(() -> NetworkClientHelper.sendCommand("/heal")); }
works/programmer/java/flood-protected-method-class.txt · Последнее изменение: 2024/09/05 01:58 — tuxapuk