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:au.org.ala.fielddata.mobile.CollectSurveyData.java

public void startLocationUpdates() {
    if (locationServiceConnection == null) {
        locationServiceConnection = new LocationServiceConnection(this, getRequiredLocationAccuracy());
        Intent intent = new Intent(this, LocationServiceHelper.class);
        bindService(intent, locationServiceConnection, Context.BIND_AUTO_CREATE);
    }/*  ww w  .j a v a2  s. co  m*/
    if (scheduler == null) {
        scheduler = Executors.newScheduledThreadPool(1);
    }

    timer = scheduler.schedule(new Runnable() {
        public void run() {
            cancelLocationUpdates();
        }
    }, GPS_TIMEOUT, TimeUnit.SECONDS);
    gpsTrackingOn = true;
}

From source file:info.raack.appliancelabeler.machinelearning.DefaultApplianceDetectionManager.java

private void startDailyRetrainingThread() {
    try {//  w ww  . j  a  v  a 2s.  com
        if (autoModelRetraining) {
            logger.info("Starting daily retraining thread...");

            scheduler = Executors.newScheduledThreadPool(1);
            scheduler.scheduleWithFixedDelay(this, 0, retrainingInterval, TimeUnit.HOURS);
        }
    } catch (Exception e) {
        logger.error("Could not schedule daily retraining thread", e);
    }
}

From source file:com.vmware.photon.controller.common.xenon.XenonRestClientTest.java

private XenonRestClient[] setupXenonRestClients(BasicServiceHost[] hosts) {
    XenonRestClient[] xenonRestClients = new XenonRestClient[hosts.length];

    for (Integer i = 0; i < hosts.length; i++) {
        StaticServerSet serverSet = new StaticServerSet(
                new InetSocketAddress(hosts[i].getPreferredAddress(), hosts[i].getPort()));
        xenonRestClients[i] = spy(new XenonRestClient(serverSet, Executors.newFixedThreadPool(1),
                Executors.newScheduledThreadPool(1)));
        xenonRestClients[i].start();/*w  ww  .jav  a 2 s .  co m*/
    }

    return xenonRestClients;
}

From source file:org.overlord.rtgov.common.elasticsearch.ElasticsearchClient.java

/**
 * Initialize the client./* w  w  w  . j av  a  2s .  c  o m*/
 *
 * @throws Exception Failed to initialize the client
 */
public void init() throws Exception {

    if (_hosts == null) {
        throw new IllegalArgumentException("Hosts property not set ");
    }

    if (_index == null) {
        throw new IllegalArgumentException("Index property not set ");
    }

    if (_type == null) {
        throw new IllegalArgumentException("Type property not set ");
    }
    if (_bulkSize > 0) {
        _scheduler = Executors.newScheduledThreadPool(1);
    }

    determineHostsAsProperty();

    /**
     * quick fix for integration tests. if hosts property set to "embedded" then a local node is start.
     * maven dependencies need to be defined correctly for this to work
     */
    //ClassLoader cl = Thread.currentThread().getContextClassLoader();

    Client client = null;

    // TODO: RTGOV-575 disabled tccl currently while OSGi not supported - but need to find a suitable
    // solution to enable index files to be retrieved from deployed module.

    //try {
    // Need to use the classloader for Elasticsearch to pick up the property files when
    // running in an OSGi environment
    //Thread.currentThread().setContextClassLoader(TransportClient.class.getClassLoader());

    if (_hosts.startsWith("embedded")) {
        try {
            // Obtain the Elasticsearch client                    
            _listener = new org.overlord.commons.services.ServiceListener<ElasticsearchNode>() {

                @Override
                public void registered(ElasticsearchNode service) {
                    if (LOG.isLoggable(Level.FINE)) {
                        LOG.fine("*********** Register embedded ElasticsearchNode");
                    }
                    try {
                        initClient(service.getClient());
                    } catch (org.elasticsearch.indices.IndexAlreadyExistsException iaee) {
                        LOG.info("Elasticsearch indexes already exist");
                    } catch (Exception e) {
                        LOG.log(Level.SEVERE, java.util.PropertyResourceBundle
                                .getBundle("rtgov-elasticsearch.Messages").getString("RTGOV-ELASTICSEARCH-3"),
                                e);
                    }
                }

                @Override
                public void unregistered(ElasticsearchNode service) {
                    if (LOG.isLoggable(Level.FINE)) {
                        LOG.fine("*********** Unregister embedded ElasticsearchNode");
                    }
                    _client = null;
                }
            };

            ServiceRegistryUtil.addServiceListener(ElasticsearchNode.class, _listener);

        } catch (Throwable e) {
            LOG.log(Level.SEVERE, java.util.PropertyResourceBundle.getBundle("rtgov-elasticsearch.Messages")
                    .getString("RTGOV-ELASTICSEARCH-3"), e);
        }
    } else {
        String[] hostsArray = _hosts.split(",");
        TransportClient c = new TransportClient();

        for (String aHostsArray : hostsArray) {
            String s = aHostsArray.trim();
            String[] host = s.split(":");

            if (LOG.isLoggable(Level.FINE)) {
                LOG.fine(" Connecting to elasticsearch host. [" + host[0] + ":" + host[1] + "]");
            }

            c = c.addTransportAddress(new InetSocketTransportAddress(host[0], new Integer(host[1])));
        }

        client = c;
    }
    //} finally {
    //Thread.currentThread().setContextClassLoader(cl);
    //}

    // Initialize outside temporary context classloader scope
    if (client != null) {
        initClient(client);
    }
}

From source file:com.yahoo.pulsar.broker.loadbalance.impl.ModularLoadManagerImpl.java

/**
 * Initializes fields which do not depend on PulsarService. initialize(PulsarService) should subsequently be called.
 *//*  ww  w .j a v  a 2 s  . c  om*/
public ModularLoadManagerImpl() {
    brokerCandidateCache = new HashSet<>();
    defaultStats = new NamespaceBundleStats();
    filterPipeline = new ArrayList<>();
    loadData = new LoadData();
    loadSheddingPipeline = new ArrayList<>();
    preallocatedBundleToBroker = new ConcurrentHashMap<>();
    primariesCache = new HashSet<>();
    scheduler = Executors.newScheduledThreadPool(1);
    sharedCache = new HashSet<>();
}

From source file:com.jose.castsocialconnector.main.MainActivity.java

private void startCheckNewDataService() {
    ScheduledExecutorService scheduleCheckMessagesTaskExecutor;
    scheduleCheckMessagesTaskExecutor = Executors.newScheduledThreadPool(5);
    if (!Config.DEBUG)
        newPhotosSchedule = scheduleCheckMessagesTaskExecutor
                .scheduleAtFixedRate(newPhotosService.getRunnable(), 0, 1, TimeUnit.MINUTES);
}

From source file:com.janrain.backplane.server.config.BackplaneConfig.java

private ScheduledExecutorService createCleanupTask() {
    long cleanupIntervalMinutes;
    logger.info("calling createCleanupTask()");
    try {//ww w.  j av a2 s .c  o  m
        cleanupIntervalMinutes = Long.valueOf(cachedGet(BpServerProperty.CLEANUP_INTERVAL_MINUTES));
    } catch (SimpleDBException e) {
        throw new RuntimeException("Error getting server property " + BpServerProperty.CLEANUP_INTERVAL_MINUTES,
                e);
    }

    ScheduledExecutorService cleanupTask = Executors.newScheduledThreadPool(1);
    cleanupTask.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {

            compileMetrics();

            try {
                getMessagesTime.time(new Callable<Object>() {
                    @Override
                    public Object call() throws Exception {
                        deleteExpiredMessages();
                        return null;
                    }
                });
            } catch (Exception e) {
                logger.error("Error while cleaning up expired messages, " + e.getMessage(), e);
            }

        }

    }, cleanupIntervalMinutes, cleanupIntervalMinutes, TimeUnit.MINUTES);

    return cleanupTask;
}

From source file:com.pinterest.teletraan.ConfigHelper.java

public static void scheduleWorkers(TeletraanServiceConfiguration configuration,
        TeletraanServiceContext serviceContext) throws Exception {
    List<WorkerConfig> workerConfigs = configuration.getWorkerConfigs();
    for (WorkerConfig config : workerConfigs) {
        String workerName = config.getName();
        Map<String, String> properties = config.getProperties();
        int defaultValue = new Random().nextInt(30);
        int initDelay = MapUtils.getIntValue(properties, "initialDelay", defaultValue);
        int period = MapUtils.getIntValue(properties, "period", DEFAULT_PERIOD);

        if (workerName.equalsIgnoreCase(StateTransitioner.class.getSimpleName())) {
            ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
            Runnable worker = new StateTransitioner(serviceContext);
            scheduler.scheduleAtFixedRate(worker, initDelay, period, TimeUnit.SECONDS);
            LOG.info("Scheduled StateTransitioner.");
        }/*w w  w . j ava2 s  . c  o m*/

        if (workerName.equalsIgnoreCase(AutoPromoter.class.getSimpleName())) {
            ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
            Runnable worker = new AutoPromoter(serviceContext);
            scheduler.scheduleAtFixedRate(worker, initDelay, period, TimeUnit.SECONDS);
            LOG.info("Scheduled AutoPromoter.");
        }

        if (workerName.equalsIgnoreCase(HotfixStateTransitioner.class.getSimpleName())) {
            ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
            Runnable worker = new HotfixStateTransitioner(serviceContext);
            scheduler.scheduleAtFixedRate(worker, initDelay, period, TimeUnit.SECONDS);
            LOG.info("Scheduled HotfixStateTransitioner.");
        }

        if (workerName.equalsIgnoreCase(SimpleAgentJanitor.class.getSimpleName())) {
            ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
            int minStaleHostThreshold = MapUtils.getIntValue(properties, "minStaleHostThreshold",
                    DEFAULT_MIN_STALE_HOST_THRESHOLD);
            int maxStaleHostThreshold = MapUtils.getIntValue(properties, "maxStaleHostThreshold",
                    DEFAULT_MAX_STALE_HOST_THRESHOLD);
            Runnable worker = new SimpleAgentJanitor(serviceContext, minStaleHostThreshold,
                    maxStaleHostThreshold);
            scheduler.scheduleAtFixedRate(worker, initDelay, period, TimeUnit.SECONDS);
            LOG.info("Scheduled SimpleAgentJanitor.");
        }

        if (workerName.equalsIgnoreCase(AgentJanitor.class.getSimpleName())) {
            ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
            int minStaleHostThreshold = MapUtils.getIntValue(properties, "minStaleHostThreshold",
                    DEFAULT_MIN_STALE_HOST_THRESHOLD);
            int maxStaleHostThreshold = MapUtils.getIntValue(properties, "maxStaleHostThreshold",
                    DEFAULT_MAX_STALE_HOST_THRESHOLD);
            int maxLaunchLatencyThreshold = MapUtils.getIntValue(properties, "maxLaunchLaencyThreshold",
                    DEFAULT_LAUNCH_LATENCY_THRESHOLD);
            Runnable worker = new AgentJanitor(serviceContext, minStaleHostThreshold, maxStaleHostThreshold,
                    maxLaunchLatencyThreshold);
            scheduler.scheduleAtFixedRate(worker, initDelay, period, TimeUnit.SECONDS);
            LOG.info("Scheduled AgentJanitor.");
        }

        // Schedule cron like jobs
        JobDetail deployJanitorJob = null;
        CronTrigger deployJanitorTrigger = null;
        if (workerName.equalsIgnoreCase(DeployJanitor.class.getSimpleName())) {
            String schedule = MapUtils.getString(properties, "schedule", DEFAULT_DEPLOY_JANITOR_SCHEDULE);
            deployJanitorJob = JobBuilder.newJob(DeployJanitor.class).withIdentity("deployJanitorJob", "group1")
                    .build();
            deployJanitorTrigger = TriggerBuilder.newTrigger().forJob(deployJanitorJob)
                    .withSchedule(CronScheduleBuilder.cronSchedule(schedule)).build();
        }
        JobDetail buildJanitorJob = null;
        CronTrigger buildJanitorTrigger = null;
        if (workerName.equalsIgnoreCase(BuildJanitor.class.getSimpleName())) {
            String schedule = MapUtils.getString(properties, "schedule", DEFAULT_BUILD_JANITOR_SCHEDULE);
            int maxDaysToKeep = MapUtils.getIntValue(properties, "minStaleHostThreshold",
                    DEFAULT_MAX_DAYS_TO_KEEP);
            int maxBuildsToKeep = MapUtils.getIntValue(properties, "maxStaleHostThreshold",
                    DEFAULT_MAX_BUILDS_TO_KEEP);
            serviceContext.setMaxDaysToKeep(maxDaysToKeep);
            serviceContext.setMaxBuildsToKeep(maxBuildsToKeep);
            buildJanitorJob = JobBuilder.newJob(BuildJanitor.class).withIdentity("buildJanitorJob", "group1")
                    .build();
            buildJanitorTrigger = TriggerBuilder.newTrigger().forJob(buildJanitorJob)
                    .withSchedule(CronScheduleBuilder.cronSchedule(schedule)).build();
        }

        if (deployJanitorTrigger != null || buildJanitorTrigger != null) {
            Scheduler cronScheduler = new StdSchedulerFactory().getScheduler();
            cronScheduler.getContext().put("serviceContext", serviceContext);
            cronScheduler.start();
            if (deployJanitorTrigger != null) {
                cronScheduler.scheduleJob(deployJanitorJob, deployJanitorTrigger);
                LOG.info("Scheduled DeployJanitor.");
            }
            if (buildJanitorTrigger != null) {
                cronScheduler.scheduleJob(buildJanitorJob, buildJanitorTrigger);
                LOG.info("Scheduled BuildJanitor.");
            }
        }

        // TODO Arcee specific workers
        if (workerName.equalsIgnoreCase(LaunchLatencyUpdater.class.getSimpleName())) {
            ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
            Runnable worker = new LaunchLatencyUpdater(serviceContext);
            scheduler.scheduleAtFixedRate(worker, initDelay, period, TimeUnit.SECONDS);
            LOG.info("Scheduled LaunchLatencyUpdater.");
        }

        if (workerName.equalsIgnoreCase(MetricsCollector.class.getSimpleName())) {
            ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
            Runnable worker = new MetricsCollector(serviceContext);
            scheduler.scheduleAtFixedRate(worker, initDelay, period, TimeUnit.SECONDS);
            LOG.info("Scheduled MetricsCollector.");
        }

        if (workerName.equalsIgnoreCase(GroupInfoCollector.class.getSimpleName())) {
            ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
            Runnable worker = new GroupInfoCollector(serviceContext);
            scheduler.scheduleAtFixedRate(worker, initDelay, period, TimeUnit.MINUTES);
            LOG.info("Scheduled GroupInfoCollector.");
        }

        if (workerName.equalsIgnoreCase(GroupInfoUpdater.class.getSimpleName())) {
            ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
            Runnable worker = new GroupInfoUpdater(serviceContext);
            scheduler.scheduleAtFixedRate(worker, initDelay, period, TimeUnit.MINUTES);
            LOG.info("Scheduled GroupInfoUpdater.");
        }

        if (workerName.equalsIgnoreCase(LaunchEventCollector.class.getSimpleName())) {
            ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
            Runnable worker = new LaunchEventCollector(serviceContext);
            scheduler.scheduleAtFixedRate(worker, initDelay, period, TimeUnit.MINUTES);
            LOG.info("Scheduled LaunchEventCollector.");
        }

        if (workerName.equalsIgnoreCase(HostTerminator.class.getSimpleName())) {
            ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
            Runnable worker = new HostTerminator(serviceContext);
            scheduler.scheduleAtFixedRate(worker, initDelay, period, TimeUnit.MINUTES);
            LOG.info("Scheduled HostTerminator.");
        }

        if (workerName.equalsIgnoreCase(HealthChecker.class.getSimpleName())) {
            ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
            Runnable worker = new HealthChecker(serviceContext);
            scheduler.scheduleAtFixedRate(worker, initDelay, period, TimeUnit.MINUTES);
            LOG.info("Scheduled HealthChecker.");
        }

        if (workerName.equalsIgnoreCase(HealthCheckInserter.class.getSimpleName())) {
            ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
            Runnable worker = new HealthCheckInserter(serviceContext);
            scheduler.scheduleAtFixedRate(worker, initDelay, period, TimeUnit.MINUTES);
            LOG.info("Scheduled HealthCheckInserter.");
        }

        if (workerName.equalsIgnoreCase(HealthCheckHostTerminator.class.getSimpleName())) {
            ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
            Runnable worker = new HealthCheckHostTerminator(serviceContext);
            scheduler.scheduleAtFixedRate(worker, initDelay, period, TimeUnit.MINUTES);
            LOG.info("Scheduled HealthCheckHostTerminator.");
        }

        if (workerName.equalsIgnoreCase(NewInstanceChecker.class.getSimpleName())) {
            ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
            Runnable worker = new NewInstanceChecker(serviceContext);
            scheduler.scheduleAtFixedRate(worker, initDelay, period, TimeUnit.MINUTES);
            LOG.info("Scheduled NewInstanceChecker.");
        }

        if (workerName.equalsIgnoreCase(LifecycleUpdator.class.getSimpleName())) {
            ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
            Runnable worker = new LifecycleUpdator(serviceContext);
            scheduler.scheduleAtFixedRate(worker, initDelay, period, TimeUnit.MINUTES);
            LOG.info("Scheduled LifecycleUpdator.");
        }

        if (workerName.equalsIgnoreCase(ReservedInstanceScheduler.class.getSimpleName())) {
            ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
            Runnable worker = new ReservedInstanceScheduler(serviceContext);
            scheduler.scheduleAtFixedRate(worker, initDelay, period, TimeUnit.MINUTES);
            LOG.info("Scheduled ReservedInstanceScheduler.");
        }
    }
}

From source file:org.apache.streams.sysomos.provider.SysomosProvider.java

@Override
public void startStream() {
    LOGGER.trace("Starting Producer");
    if (!started) {
        LOGGER.trace("Producer not started.  Initializing");
        stream = Executors.newScheduledThreadPool(getConfig().getHeartbeatIds().size() + 1);
        for (String heartbeatId : getConfig().getHeartbeatIds()) {
            Runnable task = createStream(heartbeatId);
            stream.scheduleWithFixedDelay(task, 0, this.scheduledLatency, TimeUnit.MILLISECONDS);
            LOGGER.info("Started producer task for heartbeat {}", heartbeatId);
        }//from  ww  w.j  a  v a 2s  .  co  m
        started = true;
    }
}