本文整理了Java中java.util.concurrent.ScheduledFuture
类的一些代码示例,展示了ScheduledFuture
类的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。ScheduledFuture
类的具体详情如下:
包路径:java.util.concurrent.ScheduledFuture
类名称:ScheduledFuture
[英]A delayed result-bearing action that can be cancelled. Usually a scheduled future is the result of scheduling a task with a ScheduledExecutorService.
[中]可以取消的延迟结果承载操作。通常,计划的未来是使用ScheduledExecutorService计划任务的结果。
代码示例来源:origin: ltsopensource/light-task-scheduler
public void stop() {
try {
if (start.compareAndSet(true, false)) {
scheduledFuture.cancel(true);
channelCheckExecutorService.shutdown();
offlineTaskTrackerScheduledFuture.cancel(true);
offlineTaskTrackerCheckExecutorService.shutdown();
}
LOGGER.info("Stop channel manager success!");
} catch (Throwable t) {
LOGGER.error("Stop channel manager failed!", t);
}
}
代码示例来源:origin: apache/hive
private void stopTimeoutMonitor() {
timeoutLock.lock();
try {
if (timeoutFuture != null && activeInstances.size() != 0 && timeoutFuture.cancel(false)) {
timeoutFutureRef.set(null);
LOG.info("Stopped timeout monitor task");
} else {
LOG.info("Timeout monitor task not stopped. Timeout future state: {}, #instances: {}",
timeoutFuture == null ? "null" : timeoutFuture.isDone(), activeInstances.size());
}
timeoutFuture = null;
} finally {
timeoutLock.unlock();
}
}
代码示例来源:origin: apache/incubator-dubbo
public static void cancelScheduledFuture(ScheduledFuture<?> scheduledFuture) {
ScheduledFuture<?> future = scheduledFuture;
if (future != null && !future.isCancelled()) {
future.cancel(true);
}
}
}
代码示例来源:origin: codecentric/spring-boot-admin
public void stopRegisterTask() {
if (scheduledTask != null && !scheduledTask.isDone()) {
scheduledTask.cancel(true);
LOGGER.debug("Canceled registration task");
}
}
代码示例来源:origin: alibaba/Sentinel
/**
* Start the scan task for long-idle connections.
*/
private synchronized void startScan() {
if (scanTaskFuture == null
|| scanTaskFuture.isCancelled()
|| scanTaskFuture.isDone()) {
scanTaskFuture = TIMER.scheduleAtFixedRate(
new ScanIdleConnectionTask(this), 10, 30, TimeUnit.SECONDS);
}
}
代码示例来源:origin: fabric8io/kubernetes-client
private void waitForObservedGeneration(final long observedGeneration) {
final CountDownLatch countDownLatch = new CountDownLatch(1);
final Runnable deploymentPoller = new Runnable() {
public void run() {
Deployment deployment = oper.getMandatory();
if (observedGeneration <= deployment.getStatus().getObservedGeneration()) {
countDownLatch.countDown();
}
}
};
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
ScheduledFuture poller = executor.scheduleWithFixedDelay(deploymentPoller, 0, 10, TimeUnit.MILLISECONDS);
try {
countDownLatch.await(1, TimeUnit.MINUTES);
executor.shutdown();
} catch (InterruptedException e) {
poller.cancel(true);
executor.shutdown();
throw KubernetesClientException.launderThrowable(e);
}
}
代码示例来源:origin: fabric8io/kubernetes-client
final AtomicReference<Integer> replicasRef = new AtomicReference<>(0);
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
ScheduledFuture poller = executor.scheduleWithFixedDelay(tPoller, 0, POLL_INTERVAL_MS, TimeUnit.MILLISECONDS);
try {
if (Utils.waitUntilReady(queue, rollingTimeout, rollingTimeUnit)) {
Log.debug("{}/{} pod(s) ready for {}: {} in namespace: {}.",
replicasRef.get(), count, getType().getSimpleName(), name, namespace);
} else {
Log.error("{}/{} pod(s) ready for {}: {} in namespace: {} after waiting for {} seconds so giving up",
replicasRef.get(), count, getType().getSimpleName(), name, namespace, rollingTimeUnit.toSeconds(rollingTimeout));
poller.cancel(true);
executor.shutdown();
代码示例来源:origin: fabric8io/kubernetes-client
final CountDownLatch countDownLatch = new CountDownLatch(1);
final AtomicReference<Job> atomicJob = new AtomicReference<>();
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
ScheduledFuture poller = executor.scheduleWithFixedDelay(jobPoller, 0, POLL_INTERVAL_MS, TimeUnit.MILLISECONDS);
try {
countDownLatch.await(getConfig().getScaleTimeout(), TimeUnit.MILLISECONDS);
executor.shutdown();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
poller.cancel(true);
executor.shutdown();
LOG.error("Only {}/{} pod(s) ready for Job: {} in namespace: {} - giving up",
atomicJob.get().getStatus().getActive(), atomicJob.get().getSpec().getParallelism(), atomicJob.get().getMetadata().getName(), namespace);
代码示例来源:origin: apache/nifi
private void closeStream() {
if (isClosed.get()) {
return;
}
try {
isClosed.set(true);
future.get().cancel(false);
key.cancel();
key.channel().close();
} catch (final IOException ioe) {
LOGGER.warn("Unable to cleanly close stream due to " + ioe);
} finally {
consumer.signalEndOfStream();
}
}
代码示例来源:origin: apache/hbase
/**
* For JMX to forget about all previously exported metrics.
*/
public static void clearJmxCache() {
if (LOG.isTraceEnabled()) {
LOG.trace("clearing JMX Cache" + StringUtils.stringifyException(new Exception()));
}
//If there are more then 100 ms before the executor will run then everything should be merged.
ScheduledFuture future = fut.get();
if ((future != null && (!future.isDone() && future.getDelay(TimeUnit.MILLISECONDS) > 100))) {
// BAIL OUT
return;
}
if (stopped.get()) {
return;
}
future = executor.getExecutor().schedule(new JmxCacheBusterRunnable(), 5, TimeUnit.SECONDS);
fut.set(future);
}
代码示例来源:origin: Graylog2/graylog2-server
/**
* Blocks until the Elasticsearch cluster and current write index is healthy again or the given timeout fires.
*
* @param timeout the timeout value
* @param unit the timeout unit
* @throws InterruptedException
* @throws TimeoutException
*/
public void waitForConnectedAndDeflectorHealthy(long timeout, TimeUnit unit) throws InterruptedException, TimeoutException {
LOG.debug("Waiting until the write-active index is healthy again, checking once per second.");
final CountDownLatch latch = new CountDownLatch(1);
final ScheduledFuture<?> scheduledFuture = scheduler.scheduleAtFixedRate(() -> {
try {
if (isConnected() && isDeflectorHealthy()) {
LOG.debug("Write-active index is healthy again, unblocking waiting threads.");
latch.countDown();
}
} catch (Exception ignore) {
} // to not cancel the schedule
}, 0, 1, TimeUnit.SECONDS); // TODO should this be configurable?
final boolean waitSuccess = latch.await(timeout, unit);
scheduledFuture.cancel(true); // Make sure to cancel the task to avoid task leaks!
if (!waitSuccess) {
throw new TimeoutException("Write-active index didn't get healthy within timeout");
}
}
代码示例来源:origin: jankotek/mapdb
future = s.schedule(r, randomTimeout(), randomTimeUnit());
assertFalse(future.isDone());
if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
assertSame(p, recorder.p);
future = s.schedule(c, randomTimeout(), randomTimeUnit());
assertFalse(future.isDone());
if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
assertSame(p, recorder.p);
future = s.scheduleAtFixedRate(r, randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
assertFalse(future.isDone());
if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
assertSame(p, recorder.p);
future = s.scheduleWithFixedDelay(r, randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
assertFalse(future.isDone());
if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
assertSame(p, recorder.p);
final AtomicReference<Thread> thread = new AtomicReference<>();
final Runnable setThread = () -> thread.set(Thread.currentThread());
shouldThrow();
} catch (RejectedExecutionException success) {}
assertNull(thread.get());
代码示例来源:origin: cucumber/cucumber-jvm
final AtomicBoolean done = new AtomicBoolean();
ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
ScheduledFuture<?> timer = executorService.schedule(new Runnable() {
@Override
public void run() {
} finally {
synchronized (monitor) {
done.set(true);
timer.cancel(true);
executorService.shutdownNow();
代码示例来源:origin: apache/hbase
/**
* Stops the clearing of JMX metrics and restarting the Hadoop metrics system. This is needed for
* some test environments where we manually inject sources or sinks dynamically.
*/
@VisibleForTesting
public static void stop() {
stopped.set(true);
ScheduledFuture future = fut.get();
future.cancel(false);
}
代码示例来源:origin: spring-projects/spring-framework
@Test
@SuppressWarnings({ "unchecked", "rawtypes" })
public void receiptNotReceived() {
TaskScheduler taskScheduler = mock(TaskScheduler.class);
this.session.afterConnected(this.connection);
this.session.setTaskScheduler(taskScheduler);
AtomicReference<Boolean> notReceived = new AtomicReference<>();
ScheduledFuture future = mock(ScheduledFuture.class);
when(taskScheduler.schedule(any(Runnable.class), any(Date.class))).thenReturn(future);
StompHeaders headers = new StompHeaders();
headers.setDestination("/topic/foo");
headers.setReceipt("my-receipt");
Receiptable receiptable = this.session.send(headers, "payload");
receiptable.addReceiptLostTask(() -> notReceived.set(true));
ArgumentCaptor<Runnable> taskCaptor = ArgumentCaptor.forClass(Runnable.class);
verify(taskScheduler).schedule(taskCaptor.capture(), (Date) notNull());
Runnable scheduledTask = taskCaptor.getValue();
assertNotNull(scheduledTask);
assertNull(notReceived.get());
scheduledTask.run();
assertTrue(notReceived.get());
verify(future).cancel(true);
verifyNoMoreInteractions(future);
}
代码示例来源:origin: apache/kylin
@SuppressWarnings("rawtypes")
@Ignore("why test JDK feature?")
@Test
public void testSchedulerPool() throws InterruptedException {
logger.info("testSchedulerPool");
ScheduledExecutorService fetchPool = Executors.newScheduledThreadPool(1);
final CountDownLatch countDownLatch = new CountDownLatch(3);
ScheduledFuture future = fetchPool.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
countDownLatch.countDown();
}
}, 0, 1, TimeUnit.SECONDS);
assertTrue("countDownLatch should reach zero in 15 secs", countDownLatch.await(7, TimeUnit.SECONDS));
assertTrue("future should still running", future.cancel(true));
final CountDownLatch countDownLatch2 = new CountDownLatch(3);
ScheduledFuture future2 = fetchPool.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
countDownLatch2.countDown();
throw new RuntimeException();
}
}, 0, 1, TimeUnit.SECONDS);
assertFalse("countDownLatch2 should NOT reach zero in 15 secs", countDownLatch2.await(7, TimeUnit.SECONDS));
assertFalse("future2 should has been stopped", future2.cancel(true));
}
代码示例来源:origin: apache/flink
final AtomicReference<Throwable> errorRef = new AtomicReference<>();
future.cancel(true);
if (errorRef.get() != null) {
throw new Exception(errorRef.get());
代码示例来源:origin: ltsopensource/light-task-scheduler
@Override
public void call() throws Exception {
scheduledFuture.cancel(true);
LOAD_EXECUTOR_SERVICE.shutdown();
start.set(false);
}
});
代码示例来源:origin: org.mule.services/mule-service-scheduler
@Test
@Description("Tests that a ScheduledFuture is properly cancelled for a fixed-rate Callable before it starts executing")
public void cancelFixedRateBeforeFire() throws InterruptedException {
final CountDownLatch latch = new CountDownLatch(1);
final ScheduledFuture<?> scheduled = executor.scheduleAtFixedRate(() -> {
awaitLatch(latch);
}, SECONDS.toMillis(DEFAULT_TEST_TIMEOUT_SECS), 10 * TEST_DELAY_MILLIS, MILLISECONDS);
scheduled.cancel(true);
assertCancelled(scheduled);
assertTerminationIsNotDelayed(executor);
}
代码示例来源:origin: jersey/jersey
public void reschedule(long timeOut, TimeUnit timeUnit) {
ScheduledFuture<?> future = reference.getAndSet(null);
if (future != null) {
if (future.cancel(false)) {
future = service.schedule(task, timeOut == 0 ? Integer.MAX_VALUE : timeOut,
timeOut == 0 ? TimeUnit.SECONDS : timeUnit);
reference.set(future);
}
} else {
future = service.schedule(task, timeOut == 0 ? Integer.MAX_VALUE : timeOut,
timeOut == 0 ? TimeUnit.SECONDS : timeUnit);
reference.set(future);
}
}
}
内容来源于网络,如有侵权,请联系作者删除!