java.util.concurrent.ScheduledExecutorService类的使用及代码示例

x33g5p2x  于2022-01-29 转载在 其他  
字(13.0k)|赞(0)|评价(0)|浏览(201)

本文整理了Java中java.util.concurrent.ScheduledExecutorService类的一些代码示例,展示了ScheduledExecutorService类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。ScheduledExecutorService类的具体详情如下:
包路径:java.util.concurrent.ScheduledExecutorService
类名称:ScheduledExecutorService

ScheduledExecutorService介绍

[英]An ExecutorService that can schedule commands to run after a given delay, or to execute periodically.

The schedule methods create tasks with various delays and return a task object that can be used to cancel or check execution. The scheduleAtFixedRate and scheduleWithFixedDelay methods create and execute tasks that run periodically until cancelled.

Commands submitted using the Executor#execute and ExecutorService submit methods are scheduled with a requested delay of zero. Zero and negative delays (but not periods) are also allowed in schedule methods, and are treated as requests for immediate execution.

All schedule methods accept relative delays and periods as arguments, not absolute times or dates. It is a simple matter to transform an absolute time represented as a java.util.Date to the required form. For example, to schedule at a certain future date, you can use: schedule(task,. Beware however that expiration of a relative delay need not coincide with the current Date at which the task is enabled due to network time synchronization protocols, clock drift, or other factors. The Executors class provides convenient factory methods for the ScheduledExecutorService implementations provided in this package.

Usage Example

Here is a class with a method that sets up a ScheduledExecutorService to beep every ten seconds for an hour:

import static java.util.concurrent.TimeUnit.*;public void run() { System.out.println("beep"); } 
}; 
final ScheduledFuture beeperHandle = 
scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS); 
scheduler.schedule(new Runnable()  
public void run() { beeperHandle.cancel(true); } 
}, 60 * 60, SECONDS); 
} 
}}

[中]一种ExecutorService,可以安排命令在给定延迟后运行,或定期执行。
schedule方法创建具有各种延迟的任务,并返回可用于取消或检查执行的任务对象。scheduleAtFixedRate和scheduleWithFixedDelay方法创建并执行定期运行的任务,直到取消。
使用Executor#execute和ExecutorService submit方法提交的命令的请求延迟为零。调度方法中也允许零延迟和负延迟(但不允许周期),并将其视为立即执行的请求。
所有调度方法都接受相对延迟和周期作为参数,而不是绝对时间或日期。转换用java表示的绝对时间很简单。util。按要求的表格填写日期。例如,计划在未来某个日期,你可以使用:schedule(task,。但是,请注意,由于网络时间同步协议、时钟漂移或其他因素,相对延迟的到期时间不必与启用任务的当前日期一致。Executors类为本软件包中提供的ScheduledExecutorService实现提供了方便的工厂方法。
####用法示例
下面是一个类,它有一个方法,可以设置ScheduledExecutorService,使其在一小时内每10秒发出一次嘟嘟声:

import static java.util.concurrent.TimeUnit.*;public void run() { System.out.println("beep"); } 
}; 
final ScheduledFuture beeperHandle = 
scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS); 
scheduler.schedule(new Runnable()  
public void run() { beeperHandle.cancel(true); } 
}, 60 * 60, SECONDS); 
} 
}}

代码示例

代码示例来源:origin: ReactiveX/RxJava

static void tryStart(boolean purgeEnabled) {
  if (purgeEnabled) {
    for (;;) {
      ScheduledExecutorService curr = PURGE_THREAD.get();
      if (curr != null) {
        return;
      }
      ScheduledExecutorService next = Executors.newScheduledThreadPool(1, new RxThreadFactory("RxSchedulerPurge"));
      if (PURGE_THREAD.compareAndSet(curr, next)) {
        next.scheduleAtFixedRate(new ScheduledTask(), PURGE_PERIOD_SECONDS, PURGE_PERIOD_SECONDS, TimeUnit.SECONDS);
        return;
      } else {
        next.shutdownNow();
      }
    }
  }
}

代码示例来源: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);
    }
  }
}

代码示例来源:origin: ltsopensource/light-task-scheduler

@Override
  public void call() throws Exception {
    scheduledFuture.cancel(true);
    LOAD_EXECUTOR_SERVICE.shutdown();
    start.set(false);
  }
});

代码示例来源:origin: square/okhttp

/**
 * For testing: force this web socket to release its threads.
 */
void tearDown() throws InterruptedException {
 if (cancelFuture != null) {
  cancelFuture.cancel(false);
 }
 executor.shutdown();
 executor.awaitTermination(10, TimeUnit.SECONDS);
}

代码示例来源:origin: apache/flink

void stop() {
  executor.shutdown();
  try {
    if (!executor.awaitTermination(1, TimeUnit.SECONDS)) {
      executor.shutdownNow();
    }
  } catch (InterruptedException ignored) {
    executor.shutdownNow();
  }
}

代码示例来源:origin: apache/incubator-gobblin

configuration.getClass(StressTestUtils.STRESSOR_CLASS, StressTestUtils.DEFAULT_STRESSOR_CLASS, Stressor.class);
ExecutorService executorService = Executors.newFixedThreadPool(stressorThreads);
ThrottlingPolicy policy = (ThrottlingPolicy) broker.getSharedResource(new ThrottlingPolicyFactory(),
  new SharedLimiterKey(resourceLimited));
ScheduledExecutorService reportingThread = Executors.newSingleThreadScheduledExecutor();
reportingThread.scheduleAtFixedRate(new Reporter(limiterContainer, policy), 0, 15, TimeUnit.SECONDS);
 futures.add(executorService.submit(new StressorRunner(limiterContainer.decorateLimiter(restliLimiter),
   stressor)));
for (Future<?> future : futures) {
 try {
  future.get();
 } catch (ExecutionException ee) {
  stressorFailures++;
executorService.shutdownNow();

代码示例来源:origin: OpenHFT/Chronicle-Queue

ExecutorService service1 = Executors.newSingleThreadExecutor();
ScheduledExecutorService service2 = null;
try {
  Future f = service1.submit(() -> {
    final ExcerptAppender appender = queue.acquireAppender();
  service2 = Executors.newSingleThreadScheduledExecutor();
  service2.scheduleAtFixedRate(() -> {
    Bytes b = Bytes.elasticHeapByteBuffer(128);
    final ExcerptTailer tailer = queue.createTailer();
    if (bytes == null) {
      f.get(1, TimeUnit.SECONDS);
      throw new NullPointerException("nothing in result");
    f.get(1, TimeUnit.SECONDS);
  } finally {
    bytes.release();
  service1.shutdownNow();
  if (service2 != null)
    service2.shutdownNow();

代码示例来源: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: reactor/reactor-core

@Test
public void scanSupportBuffered() throws InterruptedException {
  Executor plain = Runnable::run;
  ExecutorService plainService = Executors.newSingleThreadExecutor();
  ExecutorService threadPool = Executors.newFixedThreadPool(3);
  ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(4);
        .as("plainService").isEqualTo(null);
    scheduledThreadPool.schedule(() -> {}, 500, TimeUnit.MILLISECONDS);
    scheduledThreadPool.schedule(() -> {}, 500, TimeUnit.MILLISECONDS);
    Thread.sleep(50); //give some leeway for the pool to have consistent accounting
        .as("scheduledThreadPool").isEqualTo(2);
    threadPool.submit(() -> {
      try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); }
    });
    plainService.shutdownNow();
    unsupportedScheduledExecutorService.shutdownNow();
    threadPool.shutdownNow();
    scheduledThreadPool.shutdownNow();

代码示例来源: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: jankotek/mapdb

assertFalse(p.submit(r).isDone());
  if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
  assertSame(p, recorder.p);
    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());
final AtomicReference<Thread> thread = new AtomicReference<>();
final Runnable setThread = () -> thread.set(Thread.currentThread());

代码示例来源:origin: reactor/reactor-core

int expectedUnknown = Integer.MIN_VALUE;
ExecutorService executorService1 = Executors.newSingleThreadExecutor();
ScheduledExecutorService executorService2 =
    Executors.newSingleThreadScheduledExecutor();
ExecutorService executorService3 = Executors.newCachedThreadPool();
ExecutorService executorService4 = Executors.newFixedThreadPool(2);
ScheduledExecutorService executorService5 = Executors.newScheduledThreadPool(3);
int maxSub8 = WorkQueueProcessor.bestEffortMaxSubscribers(executorService8);
executorService1.shutdown();
executorService2.shutdown();
executorService3.shutdown();
executorService4.shutdown();
executorService5.shutdown();
executorService6.shutdown();
executorService7.shutdown();

代码示例来源: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: stackoverflow.com

ExecutorService service = Executors.newFixedThreadPool(N);
ScheduledExecutorService canceller = Executors.newSingleThreadScheduledExecutor();

public <T> Future<T> executeTask(Callable<T> c, long timeoutMS){
  final Future<T> future = service.submit(c);
  canceller.schedule(new Callable<Void>(){
    public Void call(){
     future.cancel(true);
     return null;
    }
  }, timeoutMS, TimeUnit.MILLI_SECONDS);
  return future;
}

代码示例来源:origin: ltsopensource/light-task-scheduler

public void stop() {
  try {
    if (start.compareAndSet(true, false)) {
      scheduledFuture.cancel(true);
      FIXED_EXECUTOR_SERVICE.shutdown();
    }
    LOGGER.info("Executing dead job checker stopped!");
  } catch (Throwable t) {
    LOGGER.error("Executing dead job checker stop failed!", t);
  }
}

代码示例来源:origin: prestodb/presto

shutdownHandler.schedule(() -> {
  List<TaskInfo> activeTasks = getActiveTasks();
  while (activeTasks.size() > 0) {
  Future<?> shutdownFuture = lifeCycleStopper.submit(() -> {
    lifeCycleManager.stop();
    return null;
    shutdownFuture.get(LIFECYCLE_STOP_TIMEOUT.toMillis(), MILLISECONDS);

代码示例来源:origin: stackoverflow.com

ScheduledExecutorService executor = Executors.newScheduledThreadPool(2); 
final Future handler = executor.submit(new Callable(){ ... });
executor.schedule(new Runnable(){
  public void run(){
    handler.cancel();
  }      
}, 10000, TimeUnit.MILLISECONDS);

代码示例来源:origin: prestodb/presto

@AfterMethod
public void tearDown()
{
  executor.shutdownNow();
  scheduledExecutor.shutdownNow();
}

代码示例来源: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: reactor/reactor-core

@Test
public void scanExecutorCapacity() {
  Executor plain = Runnable::run;
  ExecutorService plainService = Executors.newSingleThreadExecutor();
  ExecutorService threadPool = Executors.newFixedThreadPool(3);
  ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(4);
  DelegateServiceScheduler.UnsupportedScheduledExecutorService unsupportedScheduledExecutorService =
      new DelegateServiceScheduler.UnsupportedScheduledExecutorService(threadPool);
  try {
    assertThat(Schedulers.scanExecutor(plain, Scannable.Attr.CAPACITY))
        .as("plain").isEqualTo(null);
    assertThat(Schedulers.scanExecutor(plainService, Scannable.Attr.CAPACITY))
        .as("plainService").isEqualTo(null);
    assertThat(Schedulers.scanExecutor(threadPool, Scannable.Attr.CAPACITY))
        .as("threadPool").isEqualTo(3);
    assertThat(Schedulers.scanExecutor(scheduledThreadPool, Scannable.Attr.CAPACITY))
        .as("scheduledThreadPool").isEqualTo(Integer.MAX_VALUE);
    assertThat(Schedulers.scanExecutor(unsupportedScheduledExecutorService, Scannable.Attr.CAPACITY))
        .as("unwrapped").isEqualTo(3);
  }
  finally {
    plainService.shutdownNow();
    unsupportedScheduledExecutorService.shutdownNow();
    threadPool.shutdownNow();
    scheduledThreadPool.shutdownNow();
  }
}

相关文章