【问题标题】:How to not exceeding 60 second with java timer如何使用 java timer 不超过 60 秒
【发布时间】:2021-07-01 13:39:05
【问题描述】:

我正在使用 java 计时器,但我的问题是每次超过 60 秒,我喜欢我的代码像这样工作;

1 分 59 秒, 2分0秒..

我的代码如下。

private long lastReceivedMessage = System.currentTimeMillis();
    
@Scheduled(fixedDelayString = "${listenScheduled}", initialDelay = 1000)
private void distanceBetweenLastReceivedMessageAndCurrentTime() {
    long currentTime = System.currentTimeMillis() - lastReceivedMessage;
    logger.info("has threw 'INFO' event due to is not running as an expected since {} {} {} {} ", TimeUnit.MILLISECONDS.toMinutes(currentTime), "minutes", TimeUnit.MILLISECONDS.toSeconds(currentTime), "seconds");

【问题讨论】:

标签: java spring multithreading spring-boot java-8


【解决方案1】:

java.time

使用java.time.Instant捕捉当前时刻。

Instant then = Instant.now() ;
…
Duration d = Duration.between( then , Instant.now() ) ;
String output = d.toString() ;

toString 方法以标准ISO 8601 格式生成文本:PnYnMnDTnHnMn。我建议您使用该格式进行报告。该格式使用P 来标记开头。 T 将任何年-月-日与任何小时-分钟-秒分开。所以,两分半钟是PT2M30S

如果您坚持自己的格式,请在 Duration 上调用 to…Part 方法。

【讨论】:

  • 非常感谢你的魅力
  • @johndeltana - 这确实是解决问题的惯用方式。请记住,Duration 给出了一个有向值,即持续时间可能为负数。此外,to...Part 是随 Java-9 引入的(不是 Java-8 引入的 java.time API)。从 Trail: Date Time 了解有关现代日期时间 API 的更多信息。
【解决方案2】:

它不会自动分隔分钟和秒。另外,为了便于阅读,我建议拆分 logger.info 语句。

一种方法是先将其转换为秒,将秒和 60 的模数(余数)设置为 seconds,然后将分钟除以 minutes 值。或者您可以跳过转换并将 + 模除以 60000。

long msElapsed = 660_000; //5min 30sec

long secElapsed = msElapsed / 1000;

long minutes = secElapsed / (long) 60;

long seconds = secElapsed % 60;

System.out.printf("%d %d",(int)minutes,(int)seconds);

【讨论】:

  • 感谢您的回答,它给出了这样的输出;11 011 011 011 011 02021-07-01 17:39:38.520 DEBUG 5832 --- [ntainer#0-0-C-1]
  • currentTime /lastReceivedMessage + 60000, “秒”是你的意思吗
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-07-23
  • 2017-10-04
  • 2019-03-25
  • 2020-04-29
  • 2018-05-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多