Example usage for java.util.concurrent Executors newScheduledThreadPool

List of usage examples for java.util.concurrent Executors newScheduledThreadPool

Introduction

In this page you can find the example usage for java.util.concurrent Executors newScheduledThreadPool.

Prototype

public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) 

Source Link

Document

Creates a thread pool that can schedule commands to run after a given delay, or to execute periodically.

Usage

From source file:info.raack.appliancelabeler.datacollector.EnergyDataLoader.java

private void startRefreshTimer() {
    try {/*from   w  ww  . j  a  v  a2s.  co  m*/
        logger.info("Starting energy data loader with polling frequency of " + energyPollingFrequency);

        scheduler = Executors.newScheduledThreadPool(1);
        scheduler.scheduleWithFixedDelay(this, 0, energyPollingFrequency, TimeUnit.SECONDS);
    } catch (Exception e) {
        logger.error("Could not schedule TED data loader", e);
    }
}

From source file:fr.bmartel.speedtest.SpeedTestTask.java

/**
 * initialize thread pool./*from  w  w  w .j  a  v a 2  s .  com*/
 */
private void initThreadPool() {
    mReadExecutorService = Executors.newSingleThreadExecutor();
    mReportExecutorService = Executors.newScheduledThreadPool(SpeedTestConst.THREAD_POOL_REPORT_SIZE);
    mWriteExecutorService = Executors.newSingleThreadExecutor();
}

From source file:com.alibaba.cobar.client.datasources.ha.FailoverHotSwapDataSourceCreator.java

public DataSource createHADataSource(CobarDataSourceDescriptor descriptor) throws Exception {
    DataSource activeDataSource = descriptor.getTargetDataSource();
    DataSource standbyDataSource = descriptor.getStandbyDataSource();
    if (activeDataSource == null && standbyDataSource == null) {
        throw new IllegalArgumentException("must have at least one data source active.");
    }//from   w w w. j  av  a 2  s. c om
    if (activeDataSource == null || standbyDataSource == null) {
        logger.warn("only one data source is available for use, so no HA support.");
        if (activeDataSource == null) {
            return standbyDataSource;
        }
        return activeDataSource;
    }

    HotSwappableTargetSource targetSource = new HotSwappableTargetSource(activeDataSource);
    ProxyFactory pf = new ProxyFactory();
    pf.setInterfaces(new Class[] { DataSource.class });
    pf.setTargetSource(targetSource);

    if (isPositiveFailoverEnable()) {
        DataSource targetDetectorDataSource = descriptor.getTargetDetectorDataSource();
        DataSource standbyDetectorDataSource = descriptor.getStandbyDetectorDataSource();
        if (targetDetectorDataSource == null || standbyDetectorDataSource == null) {
            throw new IllegalArgumentException(
                    "targetDetectorDataSource or standbyDetectorDataSource can't be null if positive failover is enabled.");
        }
        // 1. create active monitoring job for failover event
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
        ExecutorService jobExecutor = Executors.newFixedThreadPool(1);
        jobExecutorRegistry.add(jobExecutor);
        FailoverMonitorJob job = new FailoverMonitorJob(jobExecutor);
        //    1.1  inject dependencies
        job.setHotSwapTargetSource(targetSource);
        job.setMasterDataSource(activeDataSource);
        job.setStandbyDataSource(standbyDataSource);
        job.setMasterDetectorDataSource(targetDetectorDataSource);
        job.setStandbyDetectorDataSource(standbyDetectorDataSource);
        job.setCurrentDetectorDataSource(targetDetectorDataSource);
        job.setDetectingRequestTimeout(getDetectingTimeoutThreshold());
        job.setDetectingSQL(getDetectingSql());
        job.setRecheckInterval(recheckInterval);
        job.setRecheckTimes(recheckTimes);
        //    1.2  start scheduling and keep reference for canceling and shutdown
        ScheduledFuture<?> future = scheduler.scheduleWithFixedDelay(job, initialDelay, monitorPeriod,
                TimeUnit.MILLISECONDS);
        schedulerFutures.put(future, scheduler);
    }

    if (isPassiveFailoverEnable()) {
        // 2. create data source proxy with passive event advice
        PassiveEventHotSwappableAdvice advice = new PassiveEventHotSwappableAdvice();
        advice.setRetryInterval(recheckInterval);
        advice.setRetryTimes(recheckTimes);
        advice.setDetectingSql(detectingSql);
        advice.setTargetSource(targetSource);
        advice.setMainDataSource(activeDataSource);
        advice.setStandbyDataSource(standbyDataSource);
        pf.addAdvice(advice);
    }

    return (DataSource) pf.getProxy();
}

From source file:info.raack.appliancedetection.evaluation.service.DefaultSimulationService.java

private void startRefreshTimer() {
    try {/*w  ww. j  av  a2 s  .co  m*/
        logger.info("Starting Simulation Service monitor...");

        scheduler = Executors.newScheduledThreadPool(1);
        scheduler.scheduleWithFixedDelay(this, 0, 1, TimeUnit.SECONDS);
    } catch (Exception e) {
        logger.error("Could not schedule TED data loader", e);
    }
}

From source file:com.datatorrent.lib.db.jdbc.AbstractJdbcPollInputOperator.java

@Override
public void setup(OperatorContext context) {
    super.setup(context);
    intializeDSLContext();// w w w .  j a v  a2s  .c om
    if (scanService == null) {
        scanService = Executors.newScheduledThreadPool(1);
    }
    execute = true;
    emitQueue = new LinkedBlockingDeque<>(queueCapacity);
    operatorId = context.getId();
    windowManager.setup(context);
}

From source file:com.ebay.myriad.Main.java

private void initRebalancerService(MyriadConfiguration cfg, Environment env, Injector injector) {
    if (cfg.isRebalancer()) {
        LOGGER.info("Initializing Rebalancer");
        rebalancerService = Executors.newScheduledThreadPool(1);
        rebalancerService.scheduleAtFixedRate(injector.getInstance(Rebalancer.class), 100, 5000,
                TimeUnit.MILLISECONDS);
    } else {//from   www.ja v a  2 s .c om
        LOGGER.info("Rebalancer is not turned on");
    }
}

From source file:com.comcast.cdn.traffic_control.traffic_router.core.dns.ZoneManager.java

protected static void initZoneCache(final TrafficRouter tr) {
    synchronized (ZoneManager.class) {
        final CacheRegister cacheRegister = tr.getCacheRegister();
        final JSONObject config = cacheRegister.getConfig();

        int poolSize = 1;
        final double scale = config.optDouble("zonemanager.threadpool.scale", 0.75);
        final int cores = Runtime.getRuntime().availableProcessors();

        if (cores > 2) {
            final Double s = Math.floor((double) cores * scale);

            if (s.intValue() > 1) {
                poolSize = s.intValue();
            }//ww  w  .  j a  va2  s .  c  om
        }

        final ExecutorService initExecutor = Executors.newFixedThreadPool(poolSize);

        final ExecutorService ze = Executors.newFixedThreadPool(poolSize);
        final ScheduledExecutorService me = Executors.newScheduledThreadPool(2); // 2 threads, one for static, one for dynamic, threads to refresh zones
        final int maintenanceInterval = config.optInt("zonemanager.cache.maintenance.interval", 300); // default 5 minutes
        final String dspec = "expireAfterAccess="
                + config.optString("zonemanager.dynamic.response.expiration", "300s"); // default to 5 minutes

        final LoadingCache<ZoneKey, Zone> dzc = createZoneCache(ZoneCacheType.DYNAMIC,
                CacheBuilderSpec.parse(dspec));
        final LoadingCache<ZoneKey, Zone> zc = createZoneCache(ZoneCacheType.STATIC);

        initZoneDirectory();

        try {
            LOGGER.info("Generating zone data");
            generateZones(tr, zc, dzc, initExecutor);
            initExecutor.shutdown();
            initExecutor.awaitTermination(5, TimeUnit.MINUTES);
            LOGGER.info("Zone generation complete");
        } catch (final InterruptedException ex) {
            LOGGER.warn("Initialization of zone data exceeded time limit of 5 minutes; continuing", ex);
        } catch (IOException ex) {
            LOGGER.fatal("Caught fatal exception while generating zone data!", ex);
        }

        me.scheduleWithFixedDelay(getMaintenanceRunnable(dzc, ZoneCacheType.DYNAMIC, maintenanceInterval), 0,
                maintenanceInterval, TimeUnit.SECONDS);
        me.scheduleWithFixedDelay(getMaintenanceRunnable(zc, ZoneCacheType.STATIC, maintenanceInterval), 0,
                maintenanceInterval, TimeUnit.SECONDS);

        final ExecutorService tze = ZoneManager.zoneExecutor;
        final ScheduledExecutorService tme = ZoneManager.zoneMaintenanceExecutor;
        final LoadingCache<ZoneKey, Zone> tzc = ZoneManager.zoneCache;
        final LoadingCache<ZoneKey, Zone> tdzc = ZoneManager.dynamicZoneCache;

        ZoneManager.zoneExecutor = ze;
        ZoneManager.zoneMaintenanceExecutor = me;
        ZoneManager.dynamicZoneCache = dzc;
        ZoneManager.zoneCache = zc;

        if (tze != null) {
            tze.shutdownNow();
        }

        if (tme != null) {
            tme.shutdownNow();
        }

        if (tzc != null) {
            tzc.invalidateAll();
        }

        if (tdzc != null) {
            tdzc.invalidateAll();
        }
    }
}

From source file:org.openremote.controller.protocol.isy99.Isy99StatusReader.java

/**
  * @param host       hostname or IP address for the ISY-99
  * @param username   username for authentication to the ISY-99
  * @param password   password for authentication to the ISY-99
  *//*  w  w  w. j  a v  a2  s.c  o m*/
public Isy99StatusReader(String host, String username, String password) {
    Runnable queryTask = new QueryTask(host, username, password);

    ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(NUM_THREADS);
    scheduler.scheduleAtFixedRate(queryTask, INITIAL_DELAY, PERIOD_BETWEEN_EXECUTIONS, TimeUnit.SECONDS);
}

From source file:at.wada811.android.library.demos.concurrent.ExecutorActivity.java

/**
 * {@link Executors#newScheduledThreadPool(int)} ?
 * //from w w w  . ja  v a2s  . c  o  m
 * <p>
 * ???????????????????
 * </p>
 */
public void newScheduledThreadPoolTest() {
    LogUtils.d();
    ScheduledExecutorService executorService = Executors.newScheduledThreadPool(2);
    executorService.schedule(new ExecutorRunnable("A", 1), 1, TimeUnit.SECONDS);
    executorService.schedule(new ExecutorRunnable("B", 1), 1, TimeUnit.SECONDS);
    executorService.schedule(new ExecutorRunnable("C", 1), 1, TimeUnit.SECONDS);
    executorService.schedule(new ExecutorRunnable("D", 1), 1, TimeUnit.SECONDS);
}

From source file:com.rks.musicx.misc.utils.Sleeptimer.java

private static void startTimer(View v, final int minutes, Context c) {
    final String impossible = c.getString(R.string.impossible);
    final String minute = c.getString(R.string.minute);
    final String minutess = c.getString(R.string.minutes);
    final String stop = c.getString(R.string.stop);
    final String minuteTxt;
    final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    final int delay = (minutes * 60) * 1000;
    if (delay == 0) {
        Toast.makeText(c, impossible, Toast.LENGTH_LONG).show();
        return;/* w  ww. j a  va2  s .  c o  m*/
    }
    if (minutes < 10) {
        minuteTxt = minute;
    } else {
        minuteTxt = minutess;
    }
    mTask = scheduler.schedule(new runner(c), delay, TimeUnit.MILLISECONDS);
    Toast.makeText(c, stop + " " + minutes + " " + minuteTxt, Toast.LENGTH_LONG).show();
    running = true;
    setState(true);
    reduceVolume(delay);
}