本文整理匯總了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;
}
}
示例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));
}
示例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));
}
}
示例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();
}
}
示例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;
}
示例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)
);
}
示例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);
}
示例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);
}
}
}
示例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);
}
}
示例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"));
}
示例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();
});
}
示例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));
}
示例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()))));
}
示例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();
}
示例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);
}