java.util.concurrent.ScheduledExecutorService.schedule()方法的使用及代码示例

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

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

ScheduledExecutorService.schedule介绍

[英]Creates and executes a one-shot action that becomes enabled after the given delay.
[中]创建并执行在给定延迟后启用的一次性操作。

代码示例

代码示例来源:origin: oracle/helidon

private synchronized void planNextTry(long afterMillis) {
  if (scheduledExecutorService == null) {
    scheduledExecutorService = Executors.newScheduledThreadPool(1);
  }
  scheduledExecutorService.schedule(this::tryPublish, afterMillis, TimeUnit.MILLISECONDS);
}

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

cacheUpdateMaster = Executors.newScheduledThreadPool(1, new ThreadFactory() {
 @Override
 public Thread newThread(Runnable r) {
cacheUpdateMaster.schedule(new CacheUpdateMasterWork(conf, shouldRunPrewarm), 0, TimeUnit.MILLISECONDS);

代码示例来源:origin: normanmaurer/netty-in-action

/**
 * Listing 7.2 Scheduling a task with a ScheduledExecutorService
 * */
public static void schedule() {
  ScheduledExecutorService executor =
      Executors.newScheduledThreadPool(10);
  ScheduledFuture<?> future = executor.schedule(
    new Runnable() {
    @Override
    public void run() {
      System.out.println("Now it is 60 seconds later");
    }
  }, 60, TimeUnit.SECONDS);
  //...
  executor.shutdown();
}

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

import static java.util.concurrent.TimeUnit.*;
class BeeperControl {
 private final ScheduledExecutorService scheduler =
   Executors.newScheduledThreadPool(1);
 public void beepForAnHour() {
   final Runnable beeper = new Runnable() {
       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: 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: apache/nifi

public ChannelListener(final int threadPoolSize, final StreamConsumerFactory consumerFactory, final BufferPool bufferPool, int timeout,
    TimeUnit unit, final boolean readSingleDatagram) throws IOException {
  this.executor = Executors.newScheduledThreadPool(threadPoolSize + 1); // need to allow for long running ChannelDispatcher thread
  this.serverSocketSelector = Selector.open();
  this.socketChannelSelector = Selector.open();
  this.bufferPool = bufferPool;
  this.initialBufferPoolSize = bufferPool.size();
  channelDispatcher = new ChannelDispatcher(serverSocketSelector, socketChannelSelector, executor, consumerFactory, bufferPool,
      timeout, unit, readSingleDatagram);
  executor.schedule(channelDispatcher, 50, TimeUnit.MILLISECONDS);
}

代码示例来源:origin: ctripcorp/apollo

@PostConstruct
public void init() {
 allEnvs = portalSettings.getAllEnvs();
 //init restTemplate
 restTemplate = restTemplateFactory.getObject();
 refreshServiceAddressService =
   Executors.newScheduledThreadPool(1, ApolloThreadFactory.create("ServiceLocator", true));
 refreshServiceAddressService.schedule(new RefreshAdminServerAddressTask(), 1, TimeUnit.MILLISECONDS);
}

代码示例来源:origin: google/guava

static TestCondition createAndSignalAfter(long delay, TimeUnit unit) {
 final TestCondition testCondition = create();
 ScheduledExecutorService scheduledPool = Executors.newScheduledThreadPool(1);
 // If signal() fails somehow, we should see a failed test, even without looking at the Future.
 Future<?> unused =
   scheduledPool.schedule(
     new Runnable() {
      @Override
      public void run() {
       testCondition.signal();
      }
     },
     delay,
     unit);
 return testCondition;
}

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

ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
MyTask myTask;
volatile boolean isStopIssued;
  executorService.schedule(taskWrapper, delay, TimeUnit.SECONDS);

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

final ScheduledExecutorService pool = Executors.newScheduledThreadPool(numThreads);
final CountDownLatch latch = new CountDownLatch(numThreads);
  pool.schedule(task, period, periodTimeUnit);

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

final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(numThreads);
@SuppressWarnings("unchecked")
final Future<Throwable>[] futures = new Future[iterations];
for (int i = 0; i < iterations; i++) {
  final Future<Throwable> future = executorService.schedule(new RunProcessor(), i * runSchedule, TimeUnit.MILLISECONDS);
  futures[i] = future;

代码示例来源:origin: Netflix/eureka

1, serverConfig.getRemoteRegionFetchThreadPoolSize(), 0, TimeUnit.SECONDS, new SynchronousQueue<Runnable>());  // use direct handoff
scheduler = Executors.newScheduledThreadPool(1,
    new ThreadFactoryBuilder()
        .setNameFormat("Eureka-RemoteRegionCacheRefresher_" + regionName + "-%d")
        .build());
scheduler.schedule(
    new TimedSupervisorTask(
        "RemoteRegionFetch_" + regionName,

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

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

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

scheduler = Executors.newScheduledThreadPool(1);
scheduler.schedule(new Runnable() {
  @Override
  public void run() {

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

@Test
public void testDetectNewFile() throws IOException, InterruptedException {
  runner.setProperty(TailFile.BASE_DIRECTORY, "target");
  runner.setProperty(TailFile.MODE, TailFile.MODE_MULTIFILE);
  runner.setProperty(TailFile.LOOKUP_FREQUENCY, "1 sec");
  runner.setProperty(TailFile.FILENAME, "log_[0-9]*\\.txt");
  runner.setProperty(TailFile.RECURSIVE, "false");
  initializeFile("target/log_1.txt", "firstLine\n");
  Runnable task = () -> {
    try {
      initializeFile("target/log_2.txt", "newFile\n");
    } catch (Exception e) {
      fail();
    }
  };
  ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
  executor.schedule(task, 2, TimeUnit.SECONDS);
  runner.setRunSchedule(2000);
  runner.run(3);
  runner.assertAllFlowFilesTransferred(TailFile.REL_SUCCESS, 2);
  assertTrue(runner.getFlowFilesForRelationship(TailFile.REL_SUCCESS).stream().anyMatch(mockFlowFile -> mockFlowFile.isContentEqual("firstLine\n")));
  assertTrue(runner.getFlowFilesForRelationship(TailFile.REL_SUCCESS).stream().anyMatch(mockFlowFile -> mockFlowFile.isContentEqual("newFile\n")));
  runner.shutdown();
}

代码示例来源:origin: biezhi/learn-java8

private static void test1() throws InterruptedException {
  ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
  Runnable           task   = () -> System.out.println("Scheduling: " + System.nanoTime());
  int                delay  = 3;
  ScheduledFuture<?> future = executor.schedule(task, delay, TimeUnit.SECONDS);
  TimeUnit.MILLISECONDS.sleep(1337);
  long remainingDelay = future.getDelay(TimeUnit.MILLISECONDS);
  System.out.printf("Remaining Delay: %sms\n", remainingDelay);
}

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

final Duration timeout = Duration.ofSeconds(30);
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

final Future<String> handler = executor.submit(new Callable() {
  @Override
  public String call() throws Exception {
    return requestDataFromModem();
  }
});

executor.schedule(new Runnable() {
  @Override
  public void run(){
    handler.cancel(true);
  }      
}, timeout.toMillis(), TimeUnit.MILLISECONDS);

executor.shutdownNow();

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

private final ScheduledExecutorService sched = Executors.newScheduledThreadPool(1);
private final ConcurrentHashMap<T, TimerTask> delayedMap = new ConcurrentHashMap<T, TimerTask>();
private final Callback<T> callback;
  prev = delayedMap.putIfAbsent(key, task);
  if (prev == null)
   sched.schedule(task, interval, TimeUnit.MILLISECONDS);
 } while (prev != null && !prev.extend()); // Exit only if new task was added to map, or existing task was extended successfully
   long remaining = dueTime - System.currentTimeMillis();
   if (remaining > 0) { // Re-schedule task
    sched.schedule(this, remaining, TimeUnit.MILLISECONDS);
   } else { // Mark as terminated and invoke callback
    dueTime = -1;

代码示例来源:origin: magefree/mage

private void btnSubmitTimerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSubmitTimerActionPerformed
  ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(5);
  timeToSubmit = 60;
  this.btnSubmitTimer.setEnabled(false);
  ScheduledFuture scheduledFuture = scheduledExecutorService.schedule((Callable) () -> {
    if (updateDeckTask != null) {
      updateDeckTask.cancel(true);
    }
    if (SessionHandler.submitDeck(tableId, deck.getDeckCardLists())) {
      removeDeckEditor();
    }
    return null;
  }, 60, TimeUnit.SECONDS);
}//GEN-LAST:event_btnSubmitTimerActionPerformed

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

ScheduledExecutorService e = Executors.newScheduledThreadPool(10)
private final long defaultWaitTimeInMinutes = 1;
public void submitTaskToWait(Runnable r){
  e.schedule(r, defaultWaitTimeInMinutes, TimeUnit.MINUTES);
}

相关文章