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

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

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

ScheduledExecutorService.scheduleWithFixedDelay介绍

[英]Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given delay between the termination of one execution and the commencement of the next. If any execution of the task encounters an exception, subsequent executions are suppressed. Otherwise, the task will only terminate via cancellation or termination of the executor.
[中]创建并执行一个周期性操作,该操作在给定的初始延迟后首先启用,然后在一次执行的终止和下一次执行的开始之间的给定延迟内启用。如果任务的任何执行遇到异常,则会抑制后续执行。否则,任务将仅通过取消或终止执行人而终止。

代码示例

代码示例来源:origin: opentripplanner/OpenTripPlanner

public GraphService(boolean autoReload) {
  if (autoReload) {
    scanExecutor = Executors.newSingleThreadScheduledExecutor();
    scanExecutor.scheduleWithFixedDelay(new Runnable() {
      @Override
      public void run() {
        autoReloadScan();
      }
    }, AUTORELOAD_PERIOD_SEC, AUTORELOAD_PERIOD_SEC, TimeUnit.SECONDS);
  }
}

代码示例来源:origin: spring-cloud-incubator/spring-cloud-alibaba

@PostConstruct
public void initTimerCheck() {
  Executors.newSingleThreadScheduledExecutor().scheduleWithFixedDelay(
      () -> onApplicationEvent(null), CHECK_INTERVAL, CHECK_INTERVAL,
      TimeUnit.SECONDS);
}

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

void startTriggerValidator(long triggerValidationIntervalMs) {
 if (scheduledExecutorService == null) {
  scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(
   new ThreadFactoryBuilder().setDaemon(true).setNameFormat("TriggerValidator").build());
  Runnable triggerValidatorRunnable = getTriggerValidatorRunnable();
  scheduledExecutorService.scheduleWithFixedDelay(triggerValidatorRunnable, triggerValidationIntervalMs,
   triggerValidationIntervalMs, TimeUnit.MILLISECONDS);
  LOG.info("Started trigger validator with interval: {} ms", triggerValidationIntervalMs);
 }
}

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

@Inject
public MySQLMetadataDAO(ObjectMapper om, DataSource dataSource, Configuration config) {
  super(om, dataSource);
  int cacheRefreshTime = config.getIntProperty(PROP_TASKDEF_CACHE_REFRESH, DEFAULT_TASKDEF_CACHE_REFRESH_SECONDS);
  Executors.newSingleThreadScheduledExecutor()
      .scheduleWithFixedDelay(this::refreshTaskDefs, cacheRefreshTime, cacheRefreshTime, TimeUnit.SECONDS);
}

代码示例来源:origin: qunarcorp/qmq

public void start() {
  executor = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("consumer-checker"));
  executor.scheduleWithFixedDelay(this, 5, 3, TimeUnit.MINUTES);
}

代码示例来源:origin: liyiorg/weixin-popular

scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
scheduledExecutorService.scheduleWithFixedDelay(new Runnable() {
  @Override
  public void run() {

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

@Override
public void start() {
 LOGGER.info("Configuration provider starting");
 Preconditions.checkState(file != null,
   "The parameter file must not be null");
 executorService = Executors.newSingleThreadScheduledExecutor(
     new ThreadFactoryBuilder().setNameFormat("conf-file-poller-%d")
       .build());
 FileWatcherRunnable fileWatcherRunnable =
   new FileWatcherRunnable(file, counterGroup);
 executorService.scheduleWithFixedDelay(fileWatcherRunnable, 0, interval,
   TimeUnit.SECONDS);
 lifecycleState = LifecycleState.START;
 LOGGER.debug("Configuration provider started");
}

代码示例来源:origin: alibaba/nacos

@PostConstruct
@SuppressWarnings("PMD.ThreadPoolCreationRule")
public void init() {
  // 每个Server都有修正usage的Job在跑,幂等
  ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat(
    "com.alibaba.nacos.CapacityManagement-%d").setDaemon(true).build();
  scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(threadFactory);
  scheduledExecutorService.scheduleWithFixedDelay(new Runnable() {
    @Override
    public void run() {
      LOGGER.info("[capacityManagement] start correct usage");
      Stopwatch stopwatch = Stopwatch.createStarted();
      correctUsage();
      LOGGER.info("[capacityManagement] end correct usage, cost: {}s", stopwatch.elapsed(TimeUnit.SECONDS));
    }
  }, PropertyUtil.getCorrectUsageDelay(), PropertyUtil.getCorrectUsageDelay(), TimeUnit.SECONDS);
}

代码示例来源:origin: hibernate/hibernate-orm

private void startIfNeeded() {
  if ( active ) {
    return;
  }
  statelock.writeLock().lock();
  try {
    if ( active ) {
      return;
    }
    executorService = Executors.newSingleThreadScheduledExecutor( new ValidationThreadFactory() );
    executorService.scheduleWithFixedDelay(
        pool::validate,
        validationInterval,
        validationInterval,
        TimeUnit.SECONDS
    );
    active = true;
  }
  finally {
    statelock.writeLock().unlock();
  }
}

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

ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
ScheduledFuture<?> handle =
    scheduler.scheduleWithFixedDelay(new Runnable() {
       public void run() { 
         throw new RuntimeException("foo");
       }
    }, 1, 10, TimeUnit.SECONDS);

// Create and Start an exception handler thread
// pass the "handle" object to the thread
// Inside the handler thread do :
....
try {
 handle.get();
} catch (ExecutionException e) {
 Exception rootException = e.getCause();
}

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

public MemIndex(final StoreConfig storeConfig, DataBlockEngine<K, V> dataBlockEngine, DataCache<K, V> dataCache) {
  this.indexMap = new ConcurrentSkipListMap<K, IndexItem<K>>();
  this.storeConfig = storeConfig;
  this.dataBlockEngine = dataBlockEngine;
  this.dataCache = dataCache;
  ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("ltsdb-index-snapshot-check-service", true));
  executorService.scheduleWithFixedDelay(new Runnable() {
    @Override
    public void run() {
      try {
        // 检查一下当改变的量达到一定量时要snapshot
        if (currentChangeNum.get() - lastSnapshotChangeNum.get() > storeConfig.getIndexSnapshotThreshold()) {
          indexSnapshot.snapshot();
        }
      } catch (Throwable t) {
        LOGGER.error("SNAPSHOT Error", t);
      }
    }
  }, 3, 2, TimeUnit.SECONDS);
}

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

public MemIndex(final StoreConfig storeConfig, DataBlockEngine<K, V> dataBlockEngine, DataCache<K, V> dataCache) {
  this.indexMap = new ConcurrentSkipListMap<K, IndexItem<K>>();
  this.storeConfig = storeConfig;
  this.dataBlockEngine = dataBlockEngine;
  this.dataCache = dataCache;
  ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("ltsdb-index-snapshot-check-service", true));
  executorService.scheduleWithFixedDelay(new Runnable() {
    @Override
    public void run() {
      try {
        // 检查一下当改变的量达到一定量时要snapshot
        if (currentChangeNum.get() - lastSnapshotChangeNum.get() > storeConfig.getIndexSnapshotThreshold()) {
          indexSnapshot.snapshot();
        }
      } catch (Throwable t) {
        LOGGER.error("SNAPSHOT Error", t);
      }
    }
  }, 3, 2, TimeUnit.SECONDS);
}

代码示例来源:origin: gzu-liyujiang/AndroidPicker

/**
 * 滚动惯性的实现
 */
private void scrollBy(float velocityY) {
  cancelFuture();
  InertiaTimerTask command = new InertiaTimerTask(this, velocityY);
  mFuture = Executors.newSingleThreadScheduledExecutor()
      .scheduleWithFixedDelay(command, 0, VELOCITY_FLING, TimeUnit.MILLISECONDS);
}

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

import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class Test1
{ 
 public static void main(String[] args)
 {
  final ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
  service.scheduleWithFixedDelay(new Runnable()
   {
    @Override
    public void run()
    {
     System.out.println(new Date());
    }
   }, 0, 1, TimeUnit.SECONDS);
 }
}

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

private void listen(WorkflowSystemTask systemTask) {
  Executors.newSingleThreadScheduledExecutor().scheduleWithFixedDelay(() -> pollAndExecute(systemTask), 1000, pollInterval, TimeUnit.MILLISECONDS);
  logger.info("Started listening for system task: {}", systemTask.getName());
}

代码示例来源:origin: elastic/elasticsearch-hadoop

void start() {
  scheduler = Executors.newSingleThreadScheduledExecutor();
  if (log != null && log.isTraceEnabled()) {
    log.trace(String.format("Starting heartbeat for %s", id));
  }
  scheduler.scheduleWithFixedDelay(new Runnable() {
    @Override
    public void run() {
      if (log != null && log.isTraceEnabled()) {
        log.trace(String.format("Heartbeat/progress sent to Hadoop for %s", id));
      }
      progressable.progress();
    }
    // start the reporter before timing out
  }, delay.getMillis(), delay.getMillis(), TimeUnit.MILLISECONDS);
}

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

@Inject
public RedisMetadataDAO(DynoProxy dynoClient, ObjectMapper objectMapper, Configuration config) {
  super(dynoClient, objectMapper, config);
  refreshTaskDefs();
  int cacheRefreshTime = config.getIntProperty("conductor.taskdef.cache.refresh.time.seconds", 60);
  Executors.newSingleThreadScheduledExecutor().scheduleWithFixedDelay(()->refreshTaskDefs(), cacheRefreshTime, cacheRefreshTime, TimeUnit.SECONDS);
}

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

if (!fsyncPerTransaction) {
 LOG.info("Sync interval = " + fsyncInterval);
 syncExecutor = Executors.newSingleThreadScheduledExecutor();
 syncExecutor.scheduleWithFixedDelay(new Runnable() {
  @Override
  public void run() {

代码示例来源:origin: gzu-liyujiang/AndroidPicker

/**
 * 平滑滚动的实现
 */
private void smoothScroll(int actionType) {
  cancelFuture();
  if (actionType == ACTION_FLING || actionType == ACTION_DRAG) {
    offset = (int) ((totalScrollY % itemHeight + itemHeight) % itemHeight);
    if ((float) offset > itemHeight / 2.0F) {//如果超过Item高度的一半,滚动到下一个Item去
      offset = (int) (itemHeight - (float) offset);
    } else {
      offset = -offset;
    }
  }
  //停止的时候,位置有偏移,不是全部都能正确停止到中间位置的,这里把文字位置挪回中间去
  SmoothScrollTimerTask command = new SmoothScrollTimerTask(this, offset);
  mFuture = Executors.newSingleThreadScheduledExecutor()
      .scheduleWithFixedDelay(command, 0, 10, TimeUnit.MILLISECONDS);
}

代码示例来源:origin: SonarSource/sonarqube

@Override
public void start() {
 executorService = Executors.newSingleThreadScheduledExecutor(
  new ThreadFactoryBuilder()
   .setNameFormat(THREAD_NAME_PREFIX + "%d")
   .setPriority(Thread.MIN_PRIORITY)
   .build());
 executorService.scheduleWithFixedDelay(() -> {
  try {
   processQueue();
  } catch (Exception e) {
   LOG.error("Error in NotificationService", e);
  }
 }, 0, delayInSeconds, TimeUnit.SECONDS);
 LOG.info("Notification service started (delay {} sec.)", delayInSeconds);
}

相关文章