需求描述
- 前5分钟,每10s 调用一次,后5分钟,每分钟调用一次(需求可继续拓展)
需求分析
- 方案一:采用两个for循环就能实现
- 优点:实现简单
- 缺点:代码容易出现冗余,后期不方便拓展
- 方案二:借助数据结构LinkedHashMap来存储,key是执行次数,value是该次数对应的休眠时间;前30次是10s,从第30次到第35次是1分钟;
代码实现
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
public class QueryFrequency {
private final static Map<Integer, Long> FREQUENCY_MAP = Collections.unmodifiableMap(
new LinkedHashMap<Integer, Long>() {
{
this.put(30, 10 * 1000L);
this.put(30 + 5, 60 * 1000L);
}
});
public static void main(String[] args) throws Exception {
Integer total = FREQUENCY_MAP.keySet()
.stream()
.max(Integer::compareTo)
.orElseThrow(() -> new Exception("not key."));
for (int i = 0; i < total; i++) {
Long millis = getSleepMillis(i);
System.out.println(i + " ==> " + millis);
sleep(millis);
}
}
private static Long getSleepMillis(int i) throws Exception {
return FREQUENCY_MAP.entrySet()
.stream()
.filter(entry -> entry.getKey() > i)
.findFirst()
.map(Map.Entry::getValue)
.orElseThrow(() -> new Exception("not value."));
}
private static void sleep(Long millis) throws InterruptedException {
Thread.sleep(millis);
}
}
效果展示
0 ==> 10000
1 ==> 10000
......
28 ==> 10000
29 ==> 10000
30 ==> 60000
31 ==> 60000
32 ==> 60000
33 ==> 60000
34 ==> 60000
总结