當前位置: 首頁>>代碼示例>>Java>>正文


Java Duration.ofMillis方法代碼示例

本文整理匯總了Java中java.time.Duration.ofMillis方法的典型用法代碼示例。如果您正苦於以下問題:Java Duration.ofMillis方法的具體用法?Java Duration.ofMillis怎麽用?Java Duration.ofMillis使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在java.time.Duration的用法示例。


在下文中一共展示了Duration.ofMillis方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: formatAsElapsed

import java.time.Duration; //導入方法依賴的package包/類
public static String formatAsElapsed() {
    Duration elapsed = Duration.ofMillis(ManagementFactory.getRuntimeMXBean().getUptime());
    long days = elapsed.toDays();
    elapsed = elapsed.minusDays(days);
    long hours = elapsed.toHours();
    elapsed = elapsed.minusHours(hours);
    long minutes = elapsed.toMinutes();
    elapsed = elapsed.minusMinutes(minutes);
    long seconds = elapsed.getSeconds();
    elapsed = elapsed.minusSeconds(seconds);
    long millis = elapsed.toMillis();

    return String.format(TIME_FORMAT,
            days,
            hours,
            minutes,
            seconds,
            millis);
}
 
開發者ID:ViniciusArnhold,項目名稱:ProjectAltaria,代碼行數:20,代碼來源:TimeUtils.java

示例2: testCustomDelayForReturnValueRetry

import java.time.Duration; //導入方法依賴的package包/類
@Test public void testCustomDelayForReturnValueRetry() throws Exception {
  TestDelay<String> delay = new TestDelay<String>() {
    @Override public Duration duration() {
      return Duration.ofMillis(1);
    }
  };
  Retryer.ForReturnValue<String> forReturnValue =
      retryer.ifReturns(s -> s.startsWith("bad"), asList(delay).stream());
  when(action.run()).thenReturn("bad").thenReturn("fixed");
  CompletionStage<String> stage = forReturnValue.retry(action::run, executor);
  elapse(Duration.ofMillis(1));
  assertCompleted(stage).isEqualTo("fixed");
  verify(action, times(2)).run();
  assertThat(delay.before).isEqualTo("bad");
  assertThat(delay.after).isEqualTo("bad");
}
 
開發者ID:google,項目名稱:mug,代碼行數:17,代碼來源:RetryerTest.java

示例3: AngerRenderer

import java.time.Duration; //導入方法依賴的package包/類
public AngerRenderer(Loop maxLoopCount) {
    super(maxLoopCount);
    emotionImage = ImageResources.emotionAnger();

    ArrayList<KeyFrameAnimation.KeyFrame> animX = new ArrayList<>();
    ArrayList<KeyFrameAnimation.KeyFrame> animY = new ArrayList<>();
    Instant now = Instant.now();
    double r = 1f / pos.length;
    for (int i = 1; i < pos.length; i++) {
        LinearAnimation x = new LinearAnimation(now, Duration.ZERO);
        x.setFromValue(ImageUtil.defaultScale(pos[i - 1][0]));
        x.setToValue(ImageUtil.defaultScale(pos[i][0]));
        animX.add(new KeyFrameAnimation.KeyFrame(r * (i - 1), r * i, x));

        LinearAnimation y = new LinearAnimation(now, Duration.ZERO);
        y.setFromValue(ImageUtil.defaultScale(pos[i][1]));
        y.setToValue(ImageUtil.defaultScale(pos[i - 1][1]));
        animY.add(new KeyFrameAnimation.KeyFrame(r * (i - 1), r * i, y));
    }

    moveX = new KeyFrameAnimation(now, Duration.ofMillis(2000), animX);
    moveY = new KeyFrameAnimation(now, Duration.ofMillis(2000), animY);

    fade.setFromValue(1);
    fade.setToValue(0);
}
 
開發者ID:orekyuu,項目名稱:Riho,代碼行數:27,代碼來源:AngerRenderer.java

示例4: eventually

import java.time.Duration; //導入方法依賴的package包/類
private void eventually(Runnable work) throws Exception {
    Duration patience = Duration.ofSeconds(1);
    Duration interval = Duration.ofMillis(15);
    int remaining = (int) (patience.toMillis() / interval.toMillis());

    while (true) {
        try {
            work.run();
            return;
        } catch (Exception | AssertionError e) {
            if (remaining-- == 0) {
                throw e;
            }
            Thread.sleep(interval.toMillis());
        }
    }
}
 
開發者ID:tim-group,項目名稱:tg-eventstore,代碼行數:18,代碼來源:EndToEndTest.java

示例5: should_wait_notasktimeout_when_no_task_found

import java.time.Duration; //導入方法依賴的package包/類
@Test
public void should_wait_notasktimeout_when_no_task_found() throws Exception {
    Duration betweenTaskTimeout = Duration.ofHours(1L);
    Duration noTaskTimeout = Duration.ofMillis(5L);

    QueueConsumer queueConsumer = mock(QueueConsumer.class);
    TaskPicker taskPicker = mock(TaskPicker.class);
    when(taskPicker.pickTask(queueConsumer)).thenReturn(null);
    TaskProcessor taskProcessor = mock(TaskProcessor.class);

    when(queueConsumer.getQueueConfig()).thenReturn(new QueueConfig(testLocation1,
            QueueSettings.builder().withBetweenTaskTimeout(betweenTaskTimeout).withNoTaskTimeout(noTaskTimeout).build()));
    QueueProcessingStatus status = new QueueRunnerInSeparateTransactions(taskPicker, taskProcessor).runQueue(queueConsumer);

    assertThat(status, equalTo(QueueProcessingStatus.SKIPPED));

    verify(taskPicker).pickTask(queueConsumer);
    verifyZeroInteractions(taskProcessor);
}
 
開發者ID:yandex-money,項目名稱:db-queue,代碼行數:20,代碼來源:QueueRunnerInSeparateTransactionsTest.java

示例6: getShouldRetry

import java.time.Duration; //導入方法依賴的package包/類
/**
 * Returns the corresponding ShouldRetry delegate.
 *
 * @return The ShouldRetry delegate.
 */
@Override
public ShouldRetry getShouldRetry() {
    return (int currentRetryCount,
            RuntimeException lastException,
            ReferenceObjectHelper<Duration> refRetryInterval) -> {
        if (currentRetryCount < this.retryCount) {
            Double delta = this.deltaBackoff == Duration.ZERO ? 0.0
                    : (Math.pow(2.0, currentRetryCount) - 1) * ThreadLocalRandom.current().nextDouble((this.deltaBackoff.getSeconds() * 0.8),
                            (this.deltaBackoff.getSeconds() * 1.2));
            Long interval = Math.min((this.minBackoff.getSeconds() + delta.intValue()), this.maxBackoff.getSeconds());
            refRetryInterval.argValue = Duration.ofMillis(interval);
            return true;
        }

        refRetryInterval.argValue = Duration.ZERO;
        return false;
    };
}
 
開發者ID:Microsoft,項目名稱:elastic-db-tools-for-java,代碼行數:24,代碼來源:ExponentialBackoff.java

示例7: getTimeRemaining

import java.time.Duration; //導入方法依賴的package包/類
/**
 * Get the remaining time, formatted nicely.
 * @return The remaining time.
 */
public String getTimeRemaining(){
	Date now = new Date();
	long remainingMillis = surveyDeadline.getTime() - now.getTime();
	Duration timeRemaining = Duration.ofMillis(remainingMillis);
	
	return DurationFormatter.formatDuration(timeRemaining);
}
 
開發者ID:erikns,項目名稱:webpoll,代碼行數:12,代碼來源:SurveyAnsweringModel.java

示例8: convertMicrosecondsToTimeString

import java.time.Duration; //導入方法依賴的package包/類
/**
 * Convert microseconds to a human readable time string.
 *
 * @param microseconds The amount of microseconds.
 * @return The human readable string representation.
 */
public static String convertMicrosecondsToTimeString(final long microseconds) {
    Duration durationMilliseconds = Duration.ofMillis(microseconds / MICROSECOND_FACTOR);
    long minutes = durationMilliseconds.toMinutes();
    long seconds = durationMilliseconds.minusMinutes(minutes).getSeconds();
    long milliseconds = durationMilliseconds.minusMinutes(minutes).minusSeconds(seconds).toMillis();
    return String.format("%dm %02ds %03dms", minutes, seconds, milliseconds);
}
 
開發者ID:trivago,項目名稱:cluecumber-report-plugin,代碼行數:14,代碼來源:RenderingUtils.java

示例9: testSubmissionTimeoutCancelsInFlightTasks

import java.time.Duration; //導入方法依賴的package包/類
@Test public void testSubmissionTimeoutCancelsInFlightTasks() throws InterruptedException {
  assumeFalse(threading == Threading.DIRECT);
  assumeTrue(mode == Mode.INTERRUPTIBLY);
  maxInFlight = 2;
  timeout = Duration.ofMillis(1);
  assertThrows(
      TimeoutException.class,
      () -> parallelize(serialTasks(
          () -> blockFor(1), // Will be interrupted
          () -> blockFor(2), // Will be interrupted
          () -> translateToString(3))));  // Times out
  shutdownAndAssertInterruptedKeys().containsExactly(1, 2);
  assertThat(translated).doesNotContainKey(3);
}
 
開發者ID:google,項目名稱:mug,代碼行數:15,代碼來源:ParallelizerTest.java

示例10: convert

import java.time.Duration; //導入方法依賴的package包/類
@Override
public Duration convert(String source) {
    source = source.trim();
    if ("0".equals(source)) {
        return Duration.ZERO;
    }
    Matcher matcher = pattern.matcher(source);
    if (!matcher.matches()) throw new IllegalArgumentException("Illegal period: " + source);
    long value = Long.parseLong(matcher.group(1));
    switch (matcher.group(2).toLowerCase()) {
        case "ns":
        case "nanos":
            return Duration.ofNanos(value);
        case "ms":
        case "msec":
        case "millis":
            return Duration.ofMillis(value);
        case "s":
        case "sec":
            return Duration.ofSeconds(value);
        case "m":
        case "min":
            return Duration.ofMinutes(value);
        case "h":
        case "hour":
        case "hours":
            return Duration.ofHours(value);
        case "d":
        case "day":
        case "days":
            return Duration.ofDays(value);
        
    }
    throw new IllegalArgumentException("Illegal unit: " + source);
}
 
開發者ID:papyrusglobal,項目名稱:state-channels,代碼行數:36,代碼來源:DurationConverter.java

示例11: parseDuration

import java.time.Duration; //導入方法依賴的package包/類
public static Duration parseDuration(String text) throws DateTimeParseException {
    if("oo".equals(text)) return INF_POSITIVE;

    // If text looks like a plain number, try to parse it as seconds,
    // but be fairly strict so we don't accidentally parse a time as
    // a number.
    if(text.matches("^\\s*-?[0-9]+(\\.[0-9]+)?\\s*$")) {
        try {
            return Duration.ofMillis((long) (1000 * Double.parseDouble(text)));
        } catch(NumberFormatException ignored) {}
    }

    return Durations.parse(text);
}
 
開發者ID:OvercastNetwork,項目名稱:ProjectAres,代碼行數:15,代碼來源:TimeUtils.java

示例12: factory_millis_long

import java.time.Duration; //導入方法依賴的package包/類
@Test(dataProvider="MillisDurationNoNanos")
public void factory_millis_long(long millis, long expectedSeconds, int expectedNanoOfSecond) {
    Duration test = Duration.ofMillis(millis);
    assertEquals(test.getSeconds(), expectedSeconds);
    assertEquals(test.getNano(), expectedNanoOfSecond);
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:7,代碼來源:TCKDuration.java

示例13: computeDelayBeforeNextRetry

import java.time.Duration; //導入方法依賴的package包/類
@Override
public Duration computeDelayBeforeNextRetry(RetryPolicyContext context) {
    int ceil = calculateExponentialDelay(context.retriesAttempted(), baseDelay, maxBackoffTime, numRetries);
    return Duration.ofMillis((ceil / 2) + random.nextInt((ceil / 2) + 1));
}
 
開發者ID:aws,項目名稱:aws-sdk-java-v2,代碼行數:6,代碼來源:EqualJitterBackoffStrategy.java

示例14: none

import java.time.Duration; //導入方法依賴的package包/類
static BackoffStrategy none() {
    return new FixedDelayBackoffStrategy(Duration.ofMillis(1));
}
 
開發者ID:aws,項目名稱:aws-sdk-java-v2,代碼行數:4,代碼來源:BackoffStrategy.java

示例15: computeDelayBeforeNextRetry

import java.time.Duration; //導入方法依賴的package包/類
@Override
public Duration computeDelayBeforeNextRetry(RetryPolicyContext context) {
    int ceil = calculateExponentialDelay(context.retriesAttempted(), baseDelay, maxBackoffTime, numRetries);
    return Duration.ofMillis(random.nextInt(ceil));
}
 
開發者ID:aws,項目名稱:aws-sdk-java-v2,代碼行數:6,代碼來源:FullJitterBackoffStrategy.java


注:本文中的java.time.Duration.ofMillis方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。