Example usage for java.util.concurrent ScheduledExecutorService scheduleAtFixedRate

List of usage examples for java.util.concurrent ScheduledExecutorService scheduleAtFixedRate

Introduction

In this page you can find the example usage for java.util.concurrent ScheduledExecutorService scheduleAtFixedRate.

Prototype

public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit);

Source Link

Document

Submits a periodic action that becomes enabled first after the given initial delay, and subsequently with the given period; that is, executions will commence after initialDelay , then initialDelay + period , then initialDelay + 2 * period , and so on.

Usage

From source file:org.apache.hadoop.hive.metastore.ReplChangeManager.java

static void scheduleCMClearer(HiveConf hiveConf) {
    if (HiveConf.getBoolVar(hiveConf, HiveConf.ConfVars.REPLCMENABLED)) {
        ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(
                new BasicThreadFactory.Builder().namingPattern("cmclearer-%d").daemon(true).build());
        executor.scheduleAtFixedRate(
                new CMClearer(hiveConf.get(HiveConf.ConfVars.REPLCMDIR.varname),
                        hiveConf.getTimeVar(ConfVars.REPLCMRETIAN, TimeUnit.SECONDS), hiveConf),
                0, hiveConf.getTimeVar(ConfVars.REPLCMINTERVAL, TimeUnit.SECONDS), TimeUnit.SECONDS);
    }/*from   w  w  w .j  a v a 2s . c  o  m*/
}

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  ww  .j a v a  2s  .  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.graylog2.Main.java

private static void initializeMessageQueue(ScheduledExecutorService scheduler, Configuration configuration) {
    // Set the maximum size if it was configured to something else than 0 (= UNLIMITED)
    if (configuration.getMessageQueueMaximumSize() != MessageQueue.SIZE_LIMIT_UNLIMITED) {
        MessageQueue.getInstance().setMaximumSize(configuration.getMessageQueueMaximumSize());
    }//from  w w w . j  av  a 2 s.c  o  m

    scheduler.scheduleAtFixedRate(new BulkIndexerThread(configuration), BulkIndexerThread.INITIAL_DELAY,
            configuration.getMessageQueuePollFrequency(), TimeUnit.SECONDS);

    LOG.info("Message queue initialized .");
}

From source file:org.wso2.carbon.device.mgt.iot.agent.kura.firealarm.core.internal.AgentCoreOperations.java

public static void startGPIOReader() {
    Runnable gpioReader = new Runnable() {
        @Override//from w  ww . j a v a2  s .  c  o m
        public void run() {
            String returnVal = readTemperatureFromPi();
            double temperature = Double.parseDouble(returnVal.split(":")[0].replace("C", ""));
            double humidity = Double.parseDouble(returnVal.split(":")[1].replace("%", ""));

            agentManager.setTemperature(temperature);
            agentManager.setHumidity(humidity);
        }
    };

    ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
    service.scheduleAtFixedRate(gpioReader, 0, agentManager.getAgentConfigs().getDataPushInterval() * 100,
            TimeUnit.MILLISECONDS);
}

From source file:com.ntsync.android.sync.activities.PaymentVerificationService.java

/**
 * Starts PaymentData Verification Timer, if not already running and
 * PaymentData is open to verify//from ww  w.  j  av  a 2s . c  o m
 * */
public static void startVerificationTimer(final Context context) {
    if (SyncUtils.hasPaymentData(context)) {
        ScheduledExecutorService scheduler = SCHEDULER_REF.get();
        if (scheduler == null || scheduler.isShutdown()) {
            scheduler = Executors.newScheduledThreadPool(1);
            SCHEDULER_REF.set(scheduler);
        } else {
            // Timer aktiv
            return;
        }
        final ScheduledExecutorService sched = scheduler;

        final Runnable verifTimer = new Runnable() {
            public void run() {
                runVerifier(context, sched);
            }
        };
        // Verificate PaymentData every 1h for

        scheduler.scheduleAtFixedRate(verifTimer, VERIFICATION_INITIAL_DELAY, VERIFICATION_INTERVAL,
                TimeUnit.SECONDS);
    }
}

From source file:org.apache.synapse.aspects.flow.statistics.log.StatisticEventProcessor.java

public static void initializeCleaningThread() {
    //Thread to consume queue and update data structures for publishing
    ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setName("Mediation Statistic Stale Entry Cleaning Task");
            return t;
        }//from w  w w.  ja  v a 2  s  .  c  om
    });
    Long eventCleanTime = Long.parseLong(
            SynapsePropertiesLoader.getPropertyValue(StatisticsConstants.FLOW_STATISTICS_EVENT_CLEAN_TIME,
                    StatisticsConstants.FLOW_STATISTICS_DEFAULT_EVENT_CLEAN_INTERVAL));
    StatisticCleaningThread statisticCleaningThread = new StatisticCleaningThread(runtimeStatistics);
    executor.scheduleAtFixedRate(statisticCleaningThread, 0, eventCleanTime, TimeUnit.MILLISECONDS);
}

From source file:org.trendafilov.odesk.notifier.Main.java

public void startup() {
    ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);
    executor.scheduleAtFixedRate(alertDeamon, 1, 1, TimeUnit.MINUTES);

    while (true) {
        executor.submit(newJobPooler);/*from www . jav  a2s .  co  m*/
        int randomDelay = 3 + (int) (Math.random() * 5);
        Logger.info(String.format("Sleeping for: [%s]", randomDelay));
        try {
            Thread.sleep(randomDelay * 1000 * 60);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:simulation.LoadBalancer.java

public LoadBalancer() {
    vehicleLists = new ArrayList<>();
    generateArrayLists();/* w  w  w. jav a2s  . c om*/
    pulseGroup = 0;

    ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
    executor.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            pulseNextGroup();
        }
    }, 5, 2, TimeUnit.SECONDS);
}

From source file:org.sample.jms.SampleQueueSender.java

public void calculate() {

    Runnable messagePerSecond = new Runnable() {
        public void run() {
            log.error("Messages per second " + messageCount);
            messageCount = 0;//from   ww  w  .j av a 2 s. c om
        }
    };

    ScheduledExecutorService executor = Executors.newScheduledThreadPool(0);
    executor.scheduleAtFixedRate(messagePerSecond, 1, 1, TimeUnit.SECONDS);
}

From source file:org.sample.jms.SampleQueueReceiver.java

public void calculate() {

    Runnable helloRunnable = new Runnable() {
        public void run() {
            System.out.println(messageCount);
            messageCount = 0;//w w w.  j  a  va  2s. c o  m
        }
    };

    ScheduledExecutorService executor = Executors.newScheduledThreadPool(0);
    executor.scheduleAtFixedRate(helloRunnable, 1, 1, TimeUnit.SECONDS);

}