我喜欢为我的项目合并时间,还有其他方法吗?例如,对于我的yml监听器,都配置分钟:1和秒:18,所以我期望的时间是78
我下面的代码;
下面是我的yml;
listener:
info:
hour: 0
minute: 0
second: 18
milliSecond: 0
我的侦听器配置如下;
@Configuration
public class EventListenerConfiguration {
@Value("${listener.info.hour}")
private int listenerInfoHour;
@Value("${listener.info.minute}")
private int listenerInfoMinute;
@Value("${listener.info.second}")
private int listenerInfoSecond;
@Value("${listener.info.milliSecond}")
private int listenerInfoMilliSecond;
public int getTotalMilliSecondTimeForInfoForSecond() {
return listenerErrorSecond * 1000 + listenerErrorMilliSecond + listenerErrorMinute * 6000 + listenerErrorHour * 360_000;
}
public int getTotalMilliSecondTimeForErrorForMinute() {
return listenerErrorMinute * 60_000 + listenerErrorMilliSecond + listenerErrorSecond * 6000 + listenerErrorHour * 360_000;
}
public int getTotalMilliSecondTimeForErrorForHour() {
return listenerErrorHour * 3_600_000 + listenerErrorMilliSecond + listenerErrorMinute * 6000 + listenerErrorSecond * 360_000;
}
我的消费类低于;
@Autowired
EventListenerConfiguration eventListenerConfiguration;
private long lastReceivedMessage = System.currentTimeMillis();
@Scheduled(fixedDelayString = "${listenScheduled}", initialDelay = 1000)
private void distanceBetweenLastReceivedMessageAndCurrentTime() {
long currentTime = System.currentTimeMillis() - lastReceivedMessage;
if (currentTime >= eventListenerConfiguration.getConcanteTotalMilliSecondTimeForErrorForSecondAndMinute()) {
publishEvent("event info", EventSeverityStatus.ERROR, EventTypeStatus.ALERT, null);
所以我尝试过";getConcanteTotalMilliSecondTimeForErrorForSecondAndMinute(("方法,但不幸的是,它没有连接秒和分钟。
public int getConcanteTotalMilliSecondTimeForErrorForSecondAndMinute() {
return getTotalMilliSecondTimeForErrorForSecond() + getTotalMilliSecondTimeForErrorForMinute();
}
不要自己计算时间。使用库方法。您的代码将更清晰、更自然地阅读,并更容易让读者相信它是正确的。在一定时间内,使用现代java日期和时间API java.time中的Duration
类。
long totalMilliseconds = Duration.ofHours(0)
.plusMinutes(1)
.plusSeconds(18)
.plusMillis(0)
.toMillis();
System.out.println("" + totalMilliseconds + " milliseconds");
这个示例片段的输出是:
78000毫秒
我假设类中的listenerInfoHour
而不是0
作为ofHours()
的参数。类似地CCD_ 5。我只是为了一个最小、简单和完整的例子,把硬编码的数字放在例子中。
链接
Oracle教程:日期时间解释如何使用java.Time.
我需要这样计算:
public int getTotalMilliSecondTime() {
return listenerErrorMilliSecond + listenerErrorSecond * 1_000 + listenerErrorMinute * 60_000 + listenerErrorHour * 3_600_000;
}