当前位置: 首页>>代码示例>>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;未经允许,请勿转载。