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


Java Duration類代碼示例

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


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

示例1: beforeEditorTyping

import java.time.Duration; //導入依賴的package包/類
@Override
public void beforeEditorTyping(char c, DataContext dataContext) {
    Instant now = Instant.now();
    Duration between = Duration.between(lastInputTime, now);
    lastInputTime = now;

    if (between.getSeconds() < comboCoolTimeSec) {
        comboCount++;
    } else {
        comboCount = 0;
        return;
    }

    RihoReactionNotifier publisher = project.getMessageBus().syncPublisher(RihoReactionNotifier.REACTION_NOTIFIER);
    switch (comboCount) {
        case 5: publisher.reaction(Reaction.of(FacePattern.SMILE1, Duration.ofSeconds(3))); break;
        case 10: publisher.reaction(Reaction.of(FacePattern.SMILE2, Duration.ofSeconds(3))); break;
        case 15: publisher.reaction(Reaction.of(FacePattern.SURPRISE, Duration.ofSeconds(5))); break;
        case 20:
        case 30: publisher.reaction(Reaction.of(FacePattern.AWAWA, Duration.ofSeconds(3))); break;
    }
}
 
開發者ID:orekyuu,項目名稱:Riho,代碼行數:23,代碼來源:IdeActionListener.java

示例2: mayCreateMoreClusters

import java.time.Duration; //導入依賴的package包/類
@Test
public void mayCreateMoreClusters() throws Exception {
  String myClientId="some-client-id";
  ImmutableList<Cluster> clusters =
      ImmutableList.of(perfectCluster(myClientId), perfectCluster(myClientId));
  SpydraArgument arguments = new SpydraArgument();
  SpydraArgument.Pooling pooling = new SpydraArgument.Pooling();
  pooling.setLimit(2);
  pooling.setMaxAge(Duration.ofMinutes(30));
  arguments.setPooling(pooling);
  arguments.setClientId(myClientId);

  assertFalse(PoolingSubmitter.Conditions.mayCreateMoreClusters(clusters, arguments));

  pooling.setLimit(3);
  assertTrue(PoolingSubmitter.Conditions.mayCreateMoreClusters(clusters, arguments));
}
 
開發者ID:spotify,項目名稱:spydra,代碼行數:18,代碼來源:PoolingTest.java

示例3: pick_task_should_delay_with_linear_strategy

import java.time.Duration; //導入依賴的package包/類
@Test
public void pick_task_should_delay_with_linear_strategy() {
    QueueLocation location = generateUniqueLocation();
    Duration expectedDelay = Duration.ofMinutes(3L);
    ZonedDateTime beforePickingTask;
    ZonedDateTime afterPickingTask;
    TaskRecord taskRecord;
    RetryTaskStrategy retryTaskStrategy = new RetryTaskStrategy.LinearBackoff(
            QueueSettings.builder().withNoTaskTimeout(Duration.ZERO)
                    .withBetweenTaskTimeout(Duration.ZERO)
                    .withRetryInterval(Duration.ofMinutes(3))
                    .build());

    Long enqueueId = executeInTransaction(() -> queueDao.enqueue(location, new EnqueueParams<>()));

    for (int attempt = 1; attempt < 10; attempt++) {
        beforePickingTask = ZonedDateTime.now();
        taskRecord = resetProcessTimeAndPick(location, retryTaskStrategy, enqueueId);
        afterPickingTask = ZonedDateTime.now();
        Assert.assertThat(taskRecord.getAttemptsCount(), equalTo((long) attempt));
        Assert.assertThat(taskRecord.getProcessTime().isAfter(beforePickingTask.plus(expectedDelay.minus(WINDOWS_OS_DELAY))), equalTo(true));
        Assert.assertThat(taskRecord.getProcessTime().isBefore(afterPickingTask.plus(expectedDelay).plus(WINDOWS_OS_DELAY)), equalTo(true));
    }
}
 
開發者ID:yandex-money,項目名稱:db-queue,代碼行數:25,代碼來源:PickTaskDaoTest.java

示例4: testExceptionWhileCallingReloadCaught

import java.time.Duration; //導入依賴的package包/類
@Test
public void testExceptionWhileCallingReloadCaught() {
    LongAdder numOfReloadCalls = new LongAdder();
    PeriodicalReloadStrategy strategy = PeriodicalReloadStrategy.builder()
            .withInterval(Duration.ofMillis(50))
            .build();

    try {
        strategy.start(() -> {
            numOfReloadCalls.increment();
            if (numOfReloadCalls.longValue() == 1) {
                throw new RuntimeException();
            }
        });

        await("Reload called more then once")
                .atMost(5, TimeUnit.SECONDS)
                .until(() -> numOfReloadCalls.longValue() > 1);
    } finally {
        strategy.stop();
    }
}
 
開發者ID:conf4j,項目名稱:conf4j,代碼行數:23,代碼來源:PeriodicalReloadStrategyTest.java

示例5: Config

import java.time.Duration; //導入依賴的package包/類
private Config(final String dataSourceSupplierClass, final String host, final int port,
    final String user,
    final Charset charset, final Optional<String> password, final Optional<String> database,
    final Optional<Integer> poolMaxSize, final Optional<Integer> poolMaxWaiters,
    final Optional<Duration> poolValidationInterval, final Optional<Set<String>> encodingClasses,
    final Optional<Integer> nioThreads, final Optional<SSL> ssl) {
  super();
  this.dataSourceSupplierClass = dataSourceSupplierClass;
  this.charset = charset;
  this.user = user;
  this.password = password;
  this.database = database;
  this.host = host;
  this.port = port;
  this.poolMaxSize = poolMaxSize;
  this.poolMaxWaiters = poolMaxWaiters;
  this.poolValidationInterval = poolValidationInterval;
  this.encodingClasses = encodingClasses.map(Collections::unmodifiableSet);
  this.nioThreads = nioThreads;
  this.ssl = ssl;
}
 
開發者ID:traneio,項目名稱:ndbc,代碼行數:22,代碼來源:Config.java

示例6: test_comparisons

import java.time.Duration; //導入依賴的package包/類
@Test
public void test_comparisons() {
    doTest_comparisons_Duration(
        Duration.ofSeconds(-2L, 0),
        Duration.ofSeconds(-2L, 999999998),
        Duration.ofSeconds(-2L, 999999999),
        Duration.ofSeconds(-1L, 0),
        Duration.ofSeconds(-1L, 1),
        Duration.ofSeconds(-1L, 999999998),
        Duration.ofSeconds(-1L, 999999999),
        Duration.ofSeconds(0L, 0),
        Duration.ofSeconds(0L, 1),
        Duration.ofSeconds(0L, 2),
        Duration.ofSeconds(0L, 999999999),
        Duration.ofSeconds(1L, 0),
        Duration.ofSeconds(2L, 0)
    );
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:19,代碼來源:TCKDuration.java

示例7: signalFx

import java.time.Duration; //導入依賴的package包/類
public static SignalFxMeterRegistry signalFx(String accessToken) {
    return new SignalFxMeterRegistry(new SignalFxConfig() {
        @Override
        public String accessToken() {
            return accessToken;
        }

        @Override
        public Duration step() {
            return Duration.ofSeconds(10);
        }

        @Override
        public String get(String k) {
            return null;
        }
    }, Clock.SYSTEM);
}
 
開發者ID:micrometer-metrics,項目名稱:micrometer,代碼行數:19,代碼來源:SampleRegistries.java

示例8: onTick

import java.time.Duration; //導入依賴的package包/類
@Override
public void onTick(Duration remaining, Duration total) {
    super.onTick(remaining, total);

    if(this.timeLimit.getShow()) {
        long secondsLeft = remaining.getSeconds();
        if(secondsLeft > 30) {
            if(this.shouldBeep()) {
                this.getMatch().playSound(NOTICE_SOUND);
            }
        }
        else if(secondsLeft > 0) {
            // Tick for the last 30 seconds
            this.getMatch().playSound(IMMINENT_SOUND);
        }
        if(secondsLeft == 5) {
            // Play the portal crescendo sound up to the last moment
            this.getMatch().playSound(CRESCENDO_SOUND);
        }
    }
}
 
開發者ID:OvercastNetwork,項目名稱:ProjectAres,代碼行數:22,代碼來源:TimeLimitCountdown.java

示例9: parseTimeFilter

import java.time.Duration; //導入依賴的package包/類
@MethodParser("time")
public Filter parseTimeFilter(Element el) throws InvalidXMLException {
    final Duration duration = XMLUtils.parseDuration(el, (Duration) null);
    if(Comparables.greaterThan(duration, Duration.ZERO)) {
        return new AllFilter(
            MatchStateFilter.started(),
            new MonostableFilter(
                duration,
                MatchStateFilter.running(),
                Optional.empty()
            ).not()
        );
    } else {
        return new MatchStateFilter(MatchState.Running, MatchState.Finished);
    }
}
 
開發者ID:OvercastNetwork,項目名稱:ProjectAres,代碼行數:17,代碼來源:FilterDefinitionParser.java

示例10: calculateNetHashRate

import java.time.Duration; //導入依賴的package包/類
@Test
public void calculateNetHashRate() {
    long ts = System.currentTimeMillis() / 1000L;
    Mockito.when(blockHeader.getTimestamp()).thenReturn(ts);

    Mockito.when(blockHeader.getCoinbase())
            .thenReturn(NOT_MY_COINBASE)
            .thenReturn(FAKE_COINBASE)
            .thenReturn(FAKE_COINBASE)
            .thenReturn(NOT_MY_COINBASE);

    Mockito.when(block.getCumulativeDifficulty()).thenReturn(BigInteger.ONE);

    HashRateCalculator hashRateCalculator = new HashRateCalculatorMining(blockStore, new RskCustomCache<>(1000L), FAKE_COINBASE);
    BigInteger hashRate = hashRateCalculator.calculateNetHashRate(Duration.ofHours(1));

    Assert.assertEquals(hashRate, new BigInteger("+4"));
}
 
開發者ID:rsksmart,項目名稱:rskj,代碼行數:19,代碼來源:HashRateCalculatorTest.java

示例11: reenqueue_should_reset_attempts

import java.time.Duration; //導入依賴的package包/類
@Test
public void reenqueue_should_reset_attempts() throws Exception {
    QueueLocation location = generateUniqueLocation();
    String actor = "abc123";
    Long enqueueId = executeInTransaction(() ->
            queueDao.enqueue(location, new EnqueueParams<String>().withActor(actor)));
    executeInTransaction(() -> {
        jdbcTemplate.update("update " + QueueDatabaseInitializer.DEFAULT_TABLE_NAME + " set attempt=10 where id=" + enqueueId);
    });

    jdbcTemplate.query("select * from " + QueueDatabaseInitializer.DEFAULT_TABLE_NAME + " where id=" + enqueueId, rs -> {
        Assert.assertThat(rs.next(), equalTo(true));
        Assert.assertThat(rs.getLong("attempt"), equalTo(10L));
        return new Object();
    });

    Boolean reenqueueResult = executeInTransaction(() ->
            queueActorDao.reenqueue(location, actor, Duration.ofHours(1L)));

    Assert.assertThat(reenqueueResult, equalTo(true));
    jdbcTemplate.query("select * from " + QueueDatabaseInitializer.DEFAULT_TABLE_NAME + " where id=" + enqueueId, rs -> {
        Assert.assertThat(rs.next(), equalTo(true));
        Assert.assertThat(rs.getLong("attempt"), equalTo(0L));
        return new Object();
    });
}
 
開發者ID:yandex-money,項目名稱:db-queue,代碼行數:27,代碼來源:QueueActorDaoTest.java

示例12: ensureConstN

import java.time.Duration; //導入依賴的package包/類
@Benchmark
public Void ensureConstN() throws CheckedFutureException {
  Future<Void> f = constVoidFuture;
  for (int i = 0; i < N.n; i++)
    f = f.ensure(ensureF);
  return f.get(Duration.ofMillis(Long.MAX_VALUE));
}
 
開發者ID:traneio,項目名稱:future,代碼行數:8,代碼來源:TraneIOFutureBenchmark.java

示例13: should_read_full_config

import java.time.Duration; //導入依賴的package包/類
@Test
public void should_read_full_config() throws Exception {
    QueueConfigsReader queueConfigsReader = new QueueConfigsReader("q");
    Collection<QueueConfig> configs = queueConfigsReader.parse(fileSystem.write(
            "q.testQueue.table=foo",
            "q.testQueue.between-task-timeout=PT0.1S",
            "q.testQueue.no-task-timeout=PT5S",
            "q.testQueue.fatal-crash-timeout=PT1H",
            "q.testQueue.thread-count=3",
            "q.testQueue.retry-type=linear",
            "q.testQueue.retry-interval=PT30S",
            "q.testQueue.processing-mode=use-external-executor",
            "q.testQueue.additional-settings.custom=val1"
    ));
    assertThat(configs, equalTo(Collections.singletonList(
            createConfig("foo", "testQueue",
                    QueueSettings.builder()
                            .withBetweenTaskTimeout(Duration.ofMillis(100L))
                            .withNoTaskTimeout(Duration.ofSeconds(5L))
                            .withThreadCount(3)
                            .withFatalCrashTimeout(Duration.ofHours(1))
                            .withRetryType(TaskRetryType.LINEAR_BACKOFF)
                            .withRetryInterval(Duration.ofSeconds(30))
                            .withProcessingMode(ProcessingMode.USE_EXTERNAL_EXECUTOR)
                            .withAdditionalSettings(new LinkedHashMap<String, String>() {{
                                put("custom", "val1");
                            }})
                            .build()))));
}
 
開發者ID:yandex-money,項目名稱:db-queue,代碼行數:30,代碼來源:QueueConfigsReaderTest.java

示例14: main

import java.time.Duration; //導入依賴的package包/類
/**
 * For Atlas: http://localhost:7101/api/v1/graph?q=name,ftimer,:eq,:dist-avg,name,timer,:eq,:dist-avg,1,:axis&s=e-5m&l=0
 */
public static void main(String[] args) {
    MeterRegistry registry = SampleConfig.myMonitoringSystem();

    Timer timer = Timer.builder("timer")
        .publishPercentiles(0.5, 0.95)
        .register(registry);

    Object placeholder = new Object();
    AtomicLong totalTimeNanos = new AtomicLong(0);
    AtomicLong totalCount = new AtomicLong(0);

    FunctionTimer.builder("ftimer", placeholder, p -> totalCount.get(), p -> totalTimeNanos.get(), TimeUnit.NANOSECONDS)
        .register(registry);

    RandomEngine r = new MersenneTwister64(0);
    Normal incomingRequests = new Normal(0, 1, r);
    Normal duration = new Normal(250, 50, r);

    AtomicInteger latencyForThisSecond = new AtomicInteger(duration.nextInt());
    Flux.interval(Duration.ofSeconds(1))
        .doOnEach(d -> latencyForThisSecond.set(duration.nextInt()))
        .subscribe();

    // the potential for an "incoming request" every 10 ms
    Flux.interval(Duration.ofMillis(10))
        .doOnEach(d -> {
            if (incomingRequests.nextDouble() + 0.4 > 0) {
                // pretend the request took some amount of time, such that the time is
                // distributed normally with a mean of 250ms
                timer.record(latencyForThisSecond.get(), TimeUnit.MILLISECONDS);
                totalCount.incrementAndGet();
                totalTimeNanos.addAndGet((long) TimeUtils.millisToUnit(latencyForThisSecond.get(), TimeUnit.NANOSECONDS));
            }
        })
        .blockLast();
}
 
開發者ID:micrometer-metrics,項目名稱:micrometer,代碼行數:40,代碼來源:FunctionTimerSample.java

示例15: ipServiceCircuitBreaker

import java.time.Duration; //導入依賴的package包/類
@Bean
public CircuitBreaker ipServiceCircuitBreaker() {
    CircuitBreakerConfig config = CircuitBreakerConfig.custom()
            .waitDurationInOpenState(Duration.ofMinutes(5))
            .ringBufferSizeInClosedState(100)
            .ringBufferSizeInHalfOpenState(30)
            .failureRateThreshold(10)
            .build();
    return CircuitBreaker.of("ipService", config);
}
 
開發者ID:ggonchar,項目名稱:reactive-spring5-example,代碼行數:11,代碼來源:CircuitBreakerConfiguration.java


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