我想编写一些代码,如果方法调用的计数在指定的时间间隔内超过最大值,则通知监听器。
假设我想知道在滑动 30 秒的时间内调用某个方法是否有点太快。
在这个方法中,我会通知这个看门狗它必须递增计数器。
我希望能够在配置的时间间隔内跟踪超过 100 个调用。
因此,看门狗将像这样实例化:new Watchdog(100, 30, TimeUnit.SECONDS, theListener);
如果是这种事情,我真的不知道如何开始编码。任何提示将不胜感激。
最佳答案
如果我很好理解的话,您需要一个或多个 WatchDogs 来跟踪在一段时间间隔内是否达到了最大数量?
我想这很适合观察者模式,其中主题(例如程序)向观察者发送通知(例如观察程序行为的看门狗)。
以下是看门狗正在观察的程序或主题:
public class Subject {
private List<WatchDog> watchDogs = new ArrayList<>();
public void add(WatchDog watchDog) {
watchDogs.add(watchDog);
}
public void execute() {
for (WatchDog watchDog : watchDogs) {
watchDog.update();
}
}
}
这是 WatchDog 的定义:
// Verifies that maxCalls is not reached between lastTimeUpdateWasCalled and
// lastTimeUpdateWasCalled + periodInSeconds
public class WatchDog {
private Date lastTimeUpdateWasCalled = null;
private int currentNumberOfCalls = 0;
private int maxCalls;
private int periodInSeconds;
public WatchDog(int maxCalls, int periodInSeconds) {
this.maxCalls = maxCalls;
this.periodInSeconds = periodInSeconds;
}
public void update() {
this.currentNumberOfCalls = this.currentNumberOfCalls + 1;
Date now = new Date();
if (lastTimeUpdateWasCalled == null) {
this.lastTimeUpdateWasCalled = now;
this.currentNumberOfCalls = 1;
return;
}
long endOfPeriodMillis = lastTimeUpdateWasCalled.getTime() + this.periodInSeconds * 1000L;
Date endOfPeriod = new Date(endOfPeriodMillis);
if (now.before(endOfPeriod)) {
this.currentNumberOfCalls = this.currentNumberOfCalls + 1;
if (this.currentNumberOfCalls >= this.maxCalls) {
System.out.println("Watchdog has detected that " + this.currentNumberOfCalls + " have been done within "
+ this.periodInSeconds + " seconds");
}
} else {
// reinitialization
this.currentNumberOfCalls = 1;
this.lastTimeUpdateWasCalled = now;
}
}
}
以下是将整体组合在一起的方法:
public class Main {
public static void main(String[] args) throws Exception {
Subject s1 = new Subject();
WatchDog w = new WatchDog(2, 2);
s1.add(w);
s1.execute();
//Thread.sleep(2000);
s1.execute();
}
}
有关观察者模式的更多信息:https://sourcemaking.com/design_patterns/observer
关于java - 如何创建一个定时看门狗来保护方法执行计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61270747/