AlarmCore { public void start(List<AlarmCallback> allCallbacks) { LocalDateTime now = LocalDateTime.now(); lastExecuteTime = now; Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(() -> { try { final List<AlarmMessage> alarmMessageList = new ArrayList<>(30); LocalDateTime checkTime = LocalDateTime.now(); int minutes = Minutes.minutesBetween(lastExecuteTime, checkTime).getMinutes(); boolean[] hasExecute = new boolean[]{false}; alarmRulesWatcher.getRunningContext().values().forEach(ruleList -> ruleList.forEach(runningRule -> { if (minutes > 0) { runningRule.moveTo(checkTime); if (checkTime.getSecondOfMinute() > 15) { hasExecute[0] = true; alarmMessageList.addAll(runningRule.check()); } } })); if (hasExecute[0]) { lastExecuteTime = checkTime.minusSeconds(checkTime.getSecondOfMinute()); } if (alarmMessageList.size() > 0) { if (alarmRulesWatcher.getCompositeRules().size() > 0) { List<AlarmMessage> messages = alarmRulesWatcher.getCompositeRuleEvaluator().evaluate(alarmRulesWatcher.getCompositeRules(), alarmMessageList); alarmMessageList.addAll(messages); } List<AlarmMessage> filteredMessages = alarmMessageList.stream().filter(msg -> !msg.isOnlyAsCondition()).collect(Collectors.toList()); allCallbacks.forEach(callback -> callback.doAlarm(filteredMessages)); } } catch (Exception e) { LOGGER.error(e.getMessage(), e); } }, 10, 10, TimeUnit.SECONDS); } AlarmCore(AlarmRulesWatcher alarmRulesWatcher); List<RunningRule> findRunningRule(String metricsName); void start(List<AlarmCallback> allCallbacks);  }
@Test public void testTriggerTimePoint() throws InterruptedException { String test = System.getProperty("AlarmCoreTest"); if (test == null) { return; } Rules emptyRules = new Rules(); emptyRules.setRules(new ArrayList<>(0)); emptyRules.setWebhooks(new ArrayList<>(0)); AlarmCore core = new AlarmCore(new AlarmRulesWatcher(emptyRules, null)); Map<String, List<RunningRule>> runningContext = Whitebox.getInternalState(core, "runningContext"); List<RunningRule> rules = new ArrayList<>(1); RunningRule mockRule = PowerMockito.mock(RunningRule.class); List<LocalDateTime> checkTime = new LinkedList<>(); final boolean[] isAdd = {true}; PowerMockito.doAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock mock) throws Throwable { if (isAdd[0]) { checkTime.add(LocalDateTime.now()); } return new ArrayList<>(0); } }).when(mockRule).check(); rules.add(mockRule); runningContext.put("mock", rules); core.start(new ArrayList<>(0)); for (int i = 0; i < 10; i++) { Thread.sleep(60 * 1000L); if (checkTime.size() >= 3) { isAdd[0] = false; Assert.assertTrue(checkTimePoints(checkTime)); break; } if (i == 9) { Assert.assertTrue(false); } } }