java.time.Duration类的使用及代码示例

x33g5p2x  于2022-01-17 转载在 其他  
字(10.1k)|赞(0)|评价(0)|浏览(401)

本文整理了Java中java.time.Duration类的一些代码示例,展示了Duration类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Duration类的具体详情如下:
包路径:java.time.Duration
类名称:Duration

Duration介绍

[英]A time-based amount of time, such as '34.5 seconds'.

This class models a quantity or amount of time in terms of seconds and nanoseconds. It can be accessed using other duration-based units, such as minutes and hours. In addition, the ChronoUnit#DAYS unit can be used and is treated as exactly equal to 24 hours, thus ignoring daylight savings effects. See Period for the date-based equivalent to this class.

A physical duration could be of infinite length. For practicality, the duration is stored with constraints similar to Instant. The duration uses nanosecond resolution with a maximum value of the seconds that can be held in a long. This is greater than the current estimated age of the universe.

The range of a duration requires the storage of a number larger than a long. To achieve this, the class stores a long representing seconds and an intrepresenting nanosecond-of-second, which will always be between 0 and 999,999,999.

The duration is measured in "seconds", but these are not necessarily identical to the scientific "SI second" definition based on atomic clocks. This difference only impacts durations measured near a leap-second and should not affect most applications. See Instant for a discussion as to the meaning of the second and time-scales.

Specification for implementors

This class is immutable and thread-safe.
[中]基于时间的时间量,例如“34.5秒”。
此类以秒和纳秒为单位对时间的数量或数量进行建模。可以使用其他基于持续时间的单位(如分钟和小时)访问它。此外,可以使用ChronoUnit#DAYS单位,并将其视为完全等于24小时,因此忽略了夏令时效应。请参阅句点,了解与此类等效的基于日期的句点。
物理持续时间可以是无限长的。出于实用性考虑,使用类似于Instant的约束来存储持续时间。持续时间使用纳秒分辨率,最大值为秒,可在长时间内保持。这比目前估计的宇宙年龄还要大。
持续时间的范围要求存储大于长时间的数字。为了实现这一点,该类存储一个表示秒的长整数和一个表示纳秒的整数,这两个整数总是介于0和999999999之间。
持续时间是以“秒”为单位测量的,但这些并不一定与基于原子钟的科学“SI秒”定义相同。此差异仅影响闰秒附近测量的持续时间,不应影响大多数应用程序。有关第二个和时间刻度的含义,请参见即时讨论。
####实施者规范
这个类是不可变的,并且是线程安全的。

代码示例

代码示例来源:origin: lets-blade/blade

public static long getCostMS(Instant start) {
  return Duration.between(start, Instant.now()).toMillis();
}

代码示例来源:origin: spring-projects/spring-framework

@Override
public ResponseCookieBuilder maxAge(long maxAgeSeconds) {
  this.maxAge = maxAgeSeconds >= 0 ? Duration.ofSeconds(maxAgeSeconds) : Duration.ofSeconds(-1);
  return this;
}

代码示例来源:origin: spring-projects/spring-framework

@Override
@Nullable
public T get(long timeout, TimeUnit unit) {
  Assert.notNull(unit, "TimeUnit must not be null");
  Duration duration = Duration.ofMillis(TimeUnit.MILLISECONDS.convert(timeout, unit));
  return this.processor.block(duration);
}

代码示例来源:origin: thinkaurelius/titan

@Override
public void sleepFor(Duration duration) throws InterruptedException {
  if (duration.isZero()) return;
  TimeUnit.NANOSECONDS.sleep(duration.toNanos());
}

代码示例来源:origin: stanfordnlp/CoreNLP

public static String elapsedTime(Date d1, Date d2){
 try{
  Duration period = Duration.between(d1.toInstant(), d2.toInstant());
  // Note: this will become easier with Java 9, using toDaysPart() etc.
  long days = period.toDays();
  period = period.minusDays(days);
  long hours = period.toHours();
  period = period.minusHours(hours);
  long minutes = period.toMinutes();
  period = period.minusMinutes(minutes);
  long seconds = period.getSeconds();
  return days + " days, " + hours + " hours, " + minutes + " minutes, " + seconds + " seconds";
 } catch(java.lang.IllegalArgumentException e) {
  log.warn(e);
 }
 return "";
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void handleReturnValueLastModified() throws Exception {
  Instant currentTime = Instant.now().truncatedTo(ChronoUnit.SECONDS);
  Instant oneMinAgo = currentTime.minusSeconds(60);
  long timestamp = currentTime.toEpochMilli();
  MockServerWebExchange exchange = MockServerWebExchange.from(get("/path").ifModifiedSince(timestamp));
  ResponseEntity<String> entity = ok().lastModified(oneMinAgo.toEpochMilli()).body("body");
  MethodParameter returnType = on(TestController.class).resolveReturnType(entity(String.class));
  HandlerResult result = handlerResult(entity, returnType);
  this.resultHandler.handleResult(exchange, result).block(Duration.ofSeconds(5));
  assertConditionalResponse(exchange, HttpStatus.NOT_MODIFIED, null, null, oneMinAgo);
}

代码示例来源:origin: spring-projects/spring-security

@Test
public void validateWhenExpiredAnd60secClockSkewThenNoErrors() {
  this.issuedAt = Instant.now().minus(Duration.ofSeconds(60));
  this.expiresAt = this.issuedAt.plus(Duration.ofSeconds(30));
  this.clockSkew = Duration.ofSeconds(60);
  assertThat(this.validateIdToken()).isEmpty();
}

代码示例来源:origin: spring-projects/spring-security

@Test
public void validateWhenIssuedAt5minAheadAnd5minClockSkewThenNoErrors() {
  this.issuedAt = Instant.now().plus(Duration.ofMinutes(5));
  this.expiresAt = this.issuedAt.plus(Duration.ofSeconds(60));
  this.clockSkew = Duration.ofMinutes(5);
  assertThat(this.validateIdToken()).isEmpty();
}

代码示例来源:origin: spring-projects/spring-framework

/**
 * Schedule the given {@link Runnable}, starting as soon as possible and invoking it with
 * the given delay between the completion of one execution and the start of the next.
 * <p>Execution will end once the scheduler shuts down or the returned
 * {@link ScheduledFuture} gets cancelled.
 * @param task the Runnable to execute whenever the trigger fires
 * @param delay the delay between the completion of one execution and the start of the next
 * @return a {@link ScheduledFuture} representing pending completion of the task
 * @throws org.springframework.core.task.TaskRejectedException if the given task was not accepted
 * for internal reasons (e.g. a pool overload handling policy or a pool shutdown in progress)
 * @since 5.0
 * @see #scheduleWithFixedDelay(Runnable, long)
 */
default ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Duration delay) {
  return scheduleWithFixedDelay(task, delay.toMillis());
}

代码示例来源:origin: MovingBlocks/Terasology

/**
 * Refresh all the metric value and the bindingMap who notes user's authorization.
 */
private void refreshMetricsPeriodic() {
  if (Duration.between(timeForRefreshMetric, Instant.now()).getSeconds() > 5) {
    metrics.refreshAllMetrics();
    timeForRefreshMetric = Instant.now();
    if (bindingMap != null) {
      refreshBindingMap();
    }
  }
}

代码示例来源:origin: spring-projects/spring-framework

@Override
public String toString() {
  StringBuilder sb = new StringBuilder();
  sb.append(getName()).append('=').append(getValue());
  if (StringUtils.hasText(getPath())) {
    sb.append("; Path=").append(getPath());
  }
  if (StringUtils.hasText(this.domain)) {
    sb.append("; Domain=").append(this.domain);
  }
  if (!this.maxAge.isNegative()) {
    sb.append("; Max-Age=").append(this.maxAge.getSeconds());
    sb.append("; Expires=");
    long millis = this.maxAge.getSeconds() > 0 ? System.currentTimeMillis() + this.maxAge.toMillis() : 0;
    sb.append(HttpHeaders.formatDate(millis));
  }
  if (this.secure) {
    sb.append("; Secure");
  }
  if (this.httpOnly) {
    sb.append("; HttpOnly");
  }
  if (StringUtils.hasText(this.sameSite)) {
    sb.append("; SameSite=").append(this.sameSite);
  }
  return sb.toString();
}

代码示例来源:origin: prestodb/presto

@Override
public void serialize(Duration duration, JsonGenerator generator, SerializerProvider provider) throws IOException
{
  if (useTimestamp(provider)) {
    if (useNanoseconds(provider)) {
      generator.writeNumber(DecimalUtils.toBigDecimal(
          duration.getSeconds(), duration.getNano()
      ));
    } else {
      generator.writeNumber(duration.toMillis());
    }
  } else {
    // Does not look like we can make any use of DateTimeFormatter here?
    generator.writeString(duration.toString());
  }
}

代码示例来源:origin: SonarSource/sonarqube

private static SnapshotDto findNearestSnapshotToTargetDate(List<SnapshotDto> snapshots, Instant targetDate) {
 // FIXME shouldn't this be the first analysis after targetDate?
 Duration bestDuration = null;
 SnapshotDto nearest = null;
 for (SnapshotDto snapshot : snapshots) {
  Instant createdAt = Instant.ofEpochMilli(snapshot.getCreatedAt());
  Duration duration = Duration.between(targetDate, createdAt).abs();
  if (bestDuration == null || duration.compareTo(bestDuration) <= 0) {
   bestDuration = duration;
   nearest = snapshot;
  }
 }
 return nearest;
}

代码示例来源:origin: MovingBlocks/Terasology

private void updatePing(EntityRef entity) {
  if (startMap.containsKey(entity) && endMap.containsKey(entity)) {
    long pingTime = Duration.between(startMap.get(entity), endMap.get(entity)).toMillis();
    pingMap.put(entity, pingTime);
  }
}

代码示例来源:origin: neo4j/neo4j

private Duration nextDurationRaw()
{
  return Duration.ofSeconds( nextLong( DAYS.getDuration().getSeconds() ), nextLong( NANOS_PER_SECOND ) );
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void maxAge() {
  Duration maxAge = Duration.ofDays(365);
  String expires = HttpHeaders.formatDate(System.currentTimeMillis() + maxAge.toMillis());
  expires = expires.substring(0, expires.indexOf(":") + 1);
  assertThat(ResponseCookie.from("id", "1fWa").maxAge(maxAge).build().toString(), allOf(
      startsWith("id=1fWa; Max-Age=31536000; Expires=" + expires),
      endsWith(" GMT")));
  assertThat(ResponseCookie.from("id", "1fWa").maxAge(maxAge.getSeconds()).build().toString(), allOf(
      startsWith("id=1fWa; Max-Age=31536000; Expires=" + expires),
      endsWith(" GMT")));
}

代码示例来源:origin: hibernate/hibernate-orm

private long getLockWaitTimeoutInSeconds(int timeoutInMilliseconds) {
  Duration duration = Duration.ofMillis( timeoutInMilliseconds );
  long timeoutInSeconds = duration.getSeconds();
  if ( duration.getNano() != 0 ) {
    LOG.info( "Changing the query timeout from " + timeoutInMilliseconds + " ms to " + timeoutInSeconds
        + " s, because HANA requires the timeout in seconds" );
  }
  return timeoutInSeconds;
}

代码示例来源:origin: spring-projects/spring-framework

private static long parseDelayAsLong(String value) throws RuntimeException {
  if (value.length() > 1 && (isP(value.charAt(0)) || isP(value.charAt(1)))) {
    return Duration.parse(value).toMillis();
  }
  return Long.parseLong(value);
}

代码示例来源:origin: neo4j/neo4j

@Test
public void shouldSlowRequestRateOnMultipleFailedAttemptsWhereAttemptIsValid()
{
  testSlowRequestRateOnMultipleFailedAttemptsWhereAttemptIsValid( 3, Duration.ofSeconds( 5 ) );
  testSlowRequestRateOnMultipleFailedAttemptsWhereAttemptIsValid( 1, Duration.ofSeconds( 11 ) );
  testSlowRequestRateOnMultipleFailedAttemptsWhereAttemptIsValid( 22, Duration.ofMinutes( 2 ) );
  testSlowRequestRateOnMultipleFailedAttemptsWhereAttemptIsValid( 42, Duration.ofDays( 4 ) );
}

代码示例来源:origin: neo4j/neo4j

@Test
public void shouldSlowRequestRateOnMultipleFailedAttempts()
{
  testSlowRequestRateOnMultipleFailedAttempts( 3, Duration.ofSeconds( 5 ) );
  testSlowRequestRateOnMultipleFailedAttempts( 1, Duration.ofSeconds( 10 ) );
  testSlowRequestRateOnMultipleFailedAttempts( 6, Duration.ofMinutes( 1 ) );
  testSlowRequestRateOnMultipleFailedAttempts( 42, Duration.ofMinutes( 2 ) );
}

相关文章