Java Code Examples for java.util.concurrent.Executors.newScheduledThreadPool()

The following are Jave code examples for showing how to use newScheduledThreadPool() of the java.util.concurrent.Executors class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: management-sdk-for-kafka   File: ZKNodeWatcher.java   View Source Code Vote up 6 votes
/**
 *
 * @param zkMonitorListener a {@link ZKMonitorCallback} instance
 * @param zkNodeAddress Zookeeper server address
 * @param zkNodePollingDelay  Amount of time in ms to poll zookeeper node
 * @param zkNodePollingInitialDelay Amount of initial time in ms before starting poll
 */
public ZKNodeWatcher(final ZKMonitorCallback zkMonitorListener,
                     final InetSocketAddress zkNodeAddress,
                     final int zkNodePollingDelay,
                     final int zkNodePollingInitialDelay) {

    validateArguments(zkMonitorListener,
            zkNodeAddress,
            zkNodePollingDelay,
            zkNodePollingInitialDelay);

    this.zkNodeAddress = zkNodeAddress;
    this.zkMonitorListener = zkMonitorListener;
    this.zkNodePollingDelay = zkNodePollingDelay;
    this.zkNodePollingInitialDelay = zkNodePollingInitialDelay;
    this.executor = Executors.newScheduledThreadPool(1);

}
 
Example 2
Project: rs-aggregator   File: TestTest.java   View Source Code Vote up 6 votes
private static void fixedDelay() {
  ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

  Runnable task = () -> {
    try {
      System.out.println("Scheduling: " + System.nanoTime());
      TimeUnit.SECONDS.sleep(2);
      System.out.println("Ready:      " +  System.nanoTime());
    }
    catch (InterruptedException e) {
      System.err.println("task interrupted");
    }
  };

  executor.scheduleWithFixedDelay(task, 0, 4, TimeUnit.SECONDS);
}
 
Example 3
Project: apollo-custom   File: PortalSettings.java   View Source Code Vote up 6 votes
@PostConstruct
private void postConstruct() {

  allEnvs = portalConfig.portalSupportedEnvs();

  for (Env env : allEnvs) {
    envStatusMark.put(env, true);
  }

  ScheduledExecutorService
      healthCheckService =
      Executors.newScheduledThreadPool(1, ApolloThreadFactory.create("EnvHealthChecker", false));

  healthCheckService
      .scheduleWithFixedDelay(new HealthCheckTask(applicationContext), 1000, HEALTH_CHECK_INTERVAL,
                              TimeUnit.MILLISECONDS);

}
 
Example 4
Project: azeroth   File: KafkaMonitor.java   View Source Code Vote up 6 votes
/**
 * 
 */
private void initCollectionTimer() {
    statScheduler = Executors.newScheduledThreadPool(1);
    statScheduler.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            lock.lock();
            try {
                //抓取kafka消费组信息
                fetchConsumerGroupFromKafkaAndZK();
                fetchProducerStatFromZK();
            } finally {
                lock.unlock();
            }
        }
    }, 1, 5, TimeUnit.SECONDS);
}
 
Example 5
Project: fresco_floodlight   File: LoadMonitor.java   View Source Code Vote up 6 votes
public static void main(String[] args) {
    final LoadMonitor monitor = new LoadMonitor(null);
    final ScheduledExecutorService scheduler =
        Executors.newScheduledThreadPool(1);
    final ScheduledFuture<?> monitorTask =
        monitor.startMonitoring(scheduler);
    final ScheduledFuture<?> printTask =
        monitor.printMonitoring(scheduler);

    // Run the tasks for 2 minutes
    scheduler.schedule(
        new Runnable() {
            public void run() {
                monitorTask.cancel(true);
                printTask.cancel(true);
            }
        }, 5*60, TimeUnit.SECONDS);
}
 
Example 6
Project: boohee_v5.6   File: CachedThreadScheduler.java   View Source Code Vote up 6 votes
CachedWorkerPool(long keepAliveTime, TimeUnit unit) {
    this.keepAliveTime = unit != null ? unit.toNanos(keepAliveTime) : 0;
    this.expiringWorkerQueue = new ConcurrentLinkedQueue();
    this.allWorkers = new CompositeSubscription();
    ScheduledExecutorService evictor = null;
    Future<?> task = null;
    if (unit != null) {
        evictor = Executors.newScheduledThreadPool(1, CachedThreadScheduler.EVICTOR_THREAD_FACTORY);
        NewThreadWorker.tryEnableCancelPolicy(evictor);
        task = evictor.scheduleWithFixedDelay(new Runnable() {
            public void run() {
                CachedWorkerPool.this.evictExpiredWorkers();
            }
        }, this.keepAliveTime, this.keepAliveTime, TimeUnit.NANOSECONDS);
    }
    this.evictorService = evictor;
    this.evictorTask = task;
}
 
Example 7
Project: ditb   File: MemStoreChunkPool.java   View Source Code Vote up 6 votes
MemStoreChunkPool(Configuration conf, int chunkSize, int maxCount,
    int initialCount) {
  this.maxCount = maxCount;
  this.chunkSize = chunkSize;
  this.reclaimedChunks = new LinkedBlockingQueue<Chunk>();
  for (int i = 0; i < initialCount; i++) {
    Chunk chunk = new Chunk(chunkSize);
    chunk.init();
    reclaimedChunks.add(chunk);
  }
  final String n = Thread.currentThread().getName();
  scheduleThreadPool = Executors.newScheduledThreadPool(1,
      new ThreadFactoryBuilder().setNameFormat(n+"-MemStoreChunkPool Statistics")
          .setDaemon(true).build());
  this.scheduleThreadPool.scheduleAtFixedRate(new StatisticsThread(this),
      statThreadPeriod, statThreadPeriod, TimeUnit.SECONDS);
}
 
Example 8
Project: JavaCommon   File: ExecutorsDemo.java   View Source Code Vote up 6 votes
static void demo() {
	ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
	// 延迟3秒执行
	scheduledThreadPool.schedule(new Runnable() {
		public void run() {
			System.out.println("delay 3 seconds");
		}
	}, 3, TimeUnit.SECONDS);

	// 表示延迟1秒后每3秒执行一次
	scheduledThreadPool.scheduleAtFixedRate(new Runnable() {
		public void run() {
			System.out.println("delay 1 seconds, and excute every 3 seconds");
		}
	}, 1, 3, TimeUnit.SECONDS);
}
 
Example 9
Project: outcomes   File: Executors3.java   View Source Code Vote up 5 votes
private static void test2() {
    ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
    Runnable task = () -> System.out.println("Scheduling: " + System.nanoTime());
    int initialDelay = 0;
    int period = 1;
    executor.scheduleAtFixedRate(task, initialDelay, period, TimeUnit.SECONDS);
}
 
Example 10
Project: org.openhab.binding.heos   File: HeosPlayerHandler.java   View Source Code Vote up 5 votes
@Override
public void initialize() {

    api.registerforChangeEvents(this);
    ScheduledExecutorService executerPool = Executors.newScheduledThreadPool(1);
    executerPool.schedule(new InitializationRunnable(), 3, TimeUnit.SECONDS);
    updateStatus(ThingStatus.ONLINE);
    super.initialize();

}
 
Example 11
Project: iTAP-controller   File: MockScheduledExecutor.java   View Source Code Vote up 5 votes
@Override
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay,
                                                 long delay, TimeUnit unit) {
    if (ses == null)
        ses = Executors.newScheduledThreadPool(1);
    try {
        return ses.scheduleWithFixedDelay(command, initialDelay, delay, unit);
    } catch (Exception e) {
        return new MockFuture<Object>(new ExecutionException(e));
    }
}
 
Example 12
Project: MoeSampleApp   File: HandlerThreadScheduler.java   View Source Code Vote up 4 votes
private IOSScheduledExecutorPool() {
    executorService = Executors.newScheduledThreadPool(1, THREAD_FACTORY);
}
 
Example 13
Project: Saber-Bot   File: ScheduleManager.java   View Source Code Vote up 4 votes
public void initScheduleSync()
{
    // every 15 minutes create a thread to check for schedules to sync
    ScheduledExecutorService syncScheduler = Executors.newScheduledThreadPool(1);
    syncScheduler.scheduleAtFixedRate( new ScheduleSyncer(), 60*15, 60*15, TimeUnit.SECONDS );
}
 
Example 14
Project: openNaEF   File: ScheduledNotifier.java   View Source Code Vote up 4 votes
private ScheduledNotifier() {
    _pool = Executors.newScheduledThreadPool(1);
    init();
}
 
Example 15
Project: sunricher-wifi-mqtt   File: TcpClient.java   View Source Code Vote up 4 votes
public void init() {
	executor = Executors.newScheduledThreadPool(1);
	future = executor.scheduleAtFixedRate(new TcpHeartBeat(this), keepAliveSeconds, keepAliveSeconds,
			TimeUnit.SECONDS);
	connect();
}
 
Example 16
Project: hadoop-oss   File: TestMetricsSourceAdapter.java   View Source Code Vote up 4 votes
/**
 * Test a race condition when updating the JMX cache (HADOOP-12482):
 * 1. Thread A reads the JMX metric every 2 JMX cache TTL. It marks the JMX
 *    cache to be updated by marking lastRecs to null. After this it adds a
 *    new key to the metrics. The next call to read should pick up this new
 *    key.
 * 2. Thread B triggers JMX metric update every 1 JMX cache TTL. It assigns
 *    lastRecs to a new object (not null any more).
 * 3. Thread A tries to read JMX metric again, sees lastRecs is not null and
 *    does not update JMX cache. As a result the read does not pickup the new
 *    metric.
 * @throws Exception
 */
@Test
public void testMetricCacheUpdateRace() throws Exception {
  // Create test source with a single metric counter of value 1.
  TestMetricsSource source = new TestMetricsSource();
  MetricsSourceBuilder sourceBuilder =
      MetricsAnnotations.newSourceBuilder(source);

  final long JMX_CACHE_TTL = 250; // ms
  List<MetricsTag> injectedTags = new ArrayList<>();
  MetricsSourceAdapter sourceAdapter =
      new MetricsSourceAdapter("test", "test",
          "test JMX cache update race condition", sourceBuilder.build(),
          injectedTags, null, null, JMX_CACHE_TTL, false);

  ScheduledExecutorService updaterExecutor =
      Executors.newScheduledThreadPool(1, new ThreadFactoryBuilder().build());
  ScheduledExecutorService readerExecutor =
      Executors.newScheduledThreadPool(1, new ThreadFactoryBuilder().build());

  final AtomicBoolean hasError = new AtomicBoolean(false);

  // Wake up every 1 JMX cache TTL to set lastRecs before updateJmxCache() is
  // called.
  SourceUpdater srcUpdater = new SourceUpdater(sourceAdapter, hasError);
  ScheduledFuture<?> updaterFuture =
      updaterExecutor.scheduleAtFixedRate(srcUpdater,
          sourceAdapter.getJmxCacheTTL(), sourceAdapter.getJmxCacheTTL(),
          TimeUnit.MILLISECONDS);
  srcUpdater.setFuture(updaterFuture);

  // Wake up every 2 JMX cache TTL so updateJmxCache() will try to update
  // JMX cache.
  SourceReader srcReader = new SourceReader(source, sourceAdapter, hasError);
  ScheduledFuture<?> readerFuture =
      readerExecutor.scheduleAtFixedRate(srcReader,
          0, // set JMX info cache at the beginning
          2 * sourceAdapter.getJmxCacheTTL(), TimeUnit.MILLISECONDS);
  srcReader.setFuture(readerFuture);

  // Let the threads do their work.
  Thread.sleep(RACE_TEST_RUNTIME);

  assertFalse("Hit error", hasError.get());

  // cleanup
  updaterExecutor.shutdownNow();
  readerExecutor.shutdownNow();
  updaterExecutor.awaitTermination(1000, TimeUnit.MILLISECONDS);
  readerExecutor.awaitTermination(1000, TimeUnit.MILLISECONDS);
}
 
Example 17
Project: hashsdn-controller   File: VotingFutureTest.java   View Source Code Vote up 4 votes
@Before
public void setUp() throws Exception {
    result = new Object();
    future = new VotingFuture<>(result, 3);
    executor = Executors.newScheduledThreadPool(1);
}
 
Example 18
Project: incubator-servicecomb-java-chassis   File: ConfigCenterClient.java   View Source Code Vote up 4 votes
private void startHeartBeatThread(WebSocket ws) {
  heartbeatTask = Executors.newScheduledThreadPool(1);
  heartbeatTask.scheduleWithFixedDelay(() -> sendHeartbeat(ws), HEARTBEAT_INTERVAL, HEARTBEAT_INTERVAL,
      TimeUnit.MILLISECONDS);
}
 
Example 19
Project: azeroth   File: ZkJobRegistry.java   View Source Code Vote up 4 votes
@Override
public void afterPropertiesSet() throws Exception {
    ZkConnection zkConnection = new ZkConnection(zkServers);
    zkClient = new ZkClient(zkConnection, 10000);
    //
    zkCheckTask = Executors.newScheduledThreadPool(1);

    zkCheckTask.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            if (schedulerConfgs.isEmpty())
                return;
            List<String> activeNodes = null;
            try {
                activeNodes = zkClient.getChildren(nodeStateParentPath);
                zkAvailabled = true;
            } catch (Exception e) {
                checkZkAvailabled();
                activeNodes = new ArrayList<>(JobContext.getContext().getActiveNodes());
            }

            if (!activeNodes.contains(JobContext.getContext().getNodeId())) {
                zkClient.createEphemeral(
                    nodeStateParentPath + "/" + JobContext.getContext().getNodeId());
                logger.info("node[{}] re-join task clusters",
                    JobContext.getContext().getNodeId());
            }
            //对节点列表排序
            Collections.sort(activeNodes);
            //本地缓存的所有jobs
            Collection<JobConfig> jobConfigs = schedulerConfgs.values();
            //
            for (JobConfig jobConfig : jobConfigs) {
                // 如果本地任务指定的执行节点不在当前实际的节点列表,重新指定
                if (!activeNodes.contains(jobConfig.getCurrentNodeId())) {
                    //指定当前节点为排序后的第一个节点
                    String newExecuteNodeId = activeNodes.get(0);
                    jobConfig.setCurrentNodeId(newExecuteNodeId);
                    logger.warn(
                        "Job[{}-{}] currentNodeId[{}] not in activeNodeList, assign new ExecuteNodeId:{}",
                        jobConfig.getGroupName(), jobConfig.getJobName(),
                        jobConfig.getCurrentNodeId(), newExecuteNodeId);
                }
            }
        }
    }, 60, 30, TimeUnit.SECONDS);
}
 
Example 20
Project: WebAndAppUITesting   File: PerfMonitor.java   View Source Code Vote up 2 votes
/**
 * Creates a thread pool that can schedule commands to run after a given
 * delay, or to execute periodically.
 * 
 * @param poolSize
 */
private void initScheduledThreadPool(int poolSize) {
	this.executor = Executors.newScheduledThreadPool(poolSize);
}