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:org.cloudifysource.usm.UniversalServiceManagerBean.java

private void reset(final boolean existingProcessFound) throws USMException, TimeoutException {
    synchronized (this.stateMutex) {

        this.state = USMState.INITIALIZING;
        logger.info("USM Started. Configuration is: " + getUsmLifecycleBean().getConfiguration());

        this.executors = Executors.newScheduledThreadPool(THREAD_POOL_SIZE);
        // Auto shutdown if this is a Test-Recipe run
        checkForRecipeTestEnvironment();

        // check for PID file
        if (existingProcessFound) {
            // found an existing process, so no need to launch
            startAsyncTasks();//w w  w.ja  v  a 2s .c o m

            // start file monitoring task too
            startFileMonitoringTask();

            this.state = USMState.RUNNING;

            return;
        }
        try {
            // Launch the process
            startProcessLifecycle();
        } catch (final USMException e) {
            logger.log(Level.SEVERE, "Process lifecycle failed to start. Shutting down the USM instance", e);
            try {
                this.shutdown();
            } catch (final Exception e2) {
                logger.log(Level.SEVERE, "While shutting down the USM due to a failure in initialization, "
                        + "the following exception occured: " + e.getMessage(), e);
            }
            throw e;
        }
    }
}

From source file:org.wso2.iot.refarch.rpi.agent.Agent.java

private void run() {
    ScheduledExecutorService dhtReaderScheduler = Executors.newScheduledThreadPool(1);
    dhtReaderScheduler.scheduleWithFixedDelay(new MonitoringDeamon(), 0, 10, TimeUnit.SECONDS);
}

From source file:org.eclipse.flux.service.common.ToolingServiceProvider.java

private void init() {
    /*/*from   w w w .j a v  a 2 s  . c  om*/
     * Get off the socket IO message listening thread
     */
    new Thread() {

        @Override
        public void run() {
            if (serviceLauncher != null) {
                serviceLauncher.init();
            }

            serviceLauncherExecutor = Executors.newFixedThreadPool(5);

            poolMaintenanceExecutor = Executors.newScheduledThreadPool(1);
            new PoolInitilizationOperation().run();

            for (IMessageHandler messageHandler : messageHandlers) {
                messageConnector.addMessageHandler(messageHandler);
            }
        }

    }.start();
}

From source file:UserInterface.PDCPrimaryDoctorRole.PDCPrimaryDoctorReportsJPanel.java

private void generateReportToggleBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_generateReportToggleBtnActionPerformed
    // TODO add your handling code here:
    if (!generateReportToggleBtn.isSelected()) {
        reportJPanel.removeAll();//w ww . ja  v a 2s.co m
        //reportJPanel.revalidate();
        reportJPanel.repaint();
        generateReportToggleBtn.setText("Generate Live Graph");
    } else {
        generateReportToggleBtn.setText("Stop Live Graph");
    }
    ScheduledExecutorService scheduledExecutorService2 = Executors.newScheduledThreadPool(5);

    Runnable task = new Runnable() {
        @Override
        public void run() {
            if (generateReportToggleBtn.isSelected()) {
                Patient patient = (Patient) patientListComboBox.getSelectedItem();
                String attribute = (String) vitalSignComboBox.getSelectedItem();
                Methods.inputVitalSigns(patient);
                populateGraphs(patient, attribute);
            } else {
                scheduledExecutorService2.shutdown();
            }

        }
    };

    ScheduledFuture scheduledTask;
    scheduledTask = scheduledExecutorService2.scheduleAtFixedRate(task, 1, 10, TimeUnit.SECONDS);

}

From source file:org.apache.kylin.job.impl.threadpool.DefaultScheduler.java

@Override
public synchronized void init(JobEngineConfig jobEngineConfig) throws SchedulerException {
    if (!initialized) {
        initialized = true;/*from   w  ww.  j  a v a  2 s .co  m*/
    } else {
        return;
    }
    String ZKConnectString = getZKConnectString(jobEngineConfig);
    if (StringUtils.isEmpty(ZKConnectString)) {
        throw new IllegalArgumentException("ZOOKEEPER_QUORUM is empty!");
    }

    this.jobEngineConfig = jobEngineConfig;
    RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
    this.zkClient = CuratorFrameworkFactory.newClient(ZKConnectString, retryPolicy);
    this.zkClient.start();
    this.sharedLock = new InterProcessMutex(zkClient, schedulerId());
    boolean hasLock = false;
    try {
        hasLock = sharedLock.acquire(3, TimeUnit.SECONDS);
    } catch (Exception e) {
        logger.warn("error acquire lock", e);
    }
    if (!hasLock) {
        logger.warn("fail to acquire lock, scheduler has not been started");
        zkClient.close();
        return;
    }
    executableManager = ExecutableManager.getInstance(jobEngineConfig.getConfig());
    //load all executable, set them to a consistent status
    fetcherPool = Executors.newScheduledThreadPool(1);
    int corePoolSize = jobEngineConfig.getMaxConcurrentJobLimit();
    jobPool = new ThreadPoolExecutor(corePoolSize, corePoolSize, Long.MAX_VALUE, TimeUnit.DAYS,
            new SynchronousQueue<Runnable>());
    context = new DefaultContext(Maps.<String, Executable>newConcurrentMap(), jobEngineConfig.getConfig());

    for (AbstractExecutable executable : executableManager.getAllExecutables()) {
        if (executable.getStatus() == ExecutableState.READY) {
            executableManager.updateJobOutput(executable.getId(), ExecutableState.ERROR, null,
                    "scheduler initializing work to reset job to ERROR status");
        }
    }
    executableManager.updateAllRunningJobsToError();

    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            logger.debug("Closing zk connection");
            try {
                shutdown();
            } catch (SchedulerException e) {
                logger.error("error shutdown scheduler", e);
            }
        }
    });

    fetcherPool.scheduleAtFixedRate(new FetcherRunner(), 10,
            ExecutableConstants.DEFAULT_SCHEDULER_INTERVAL_SECONDS, TimeUnit.SECONDS);
    hasStarted = true;
}

From source file:org.openhab.binding.nikobus.internal.NikobusBinding.java

/**
 * Start an automatic refresh scheduler.
 *//*from w w  w  .  j  a  va  2  s.  c  o  m*/
private void startRefreshScheduler() {

    // stop any running instance..
    if (refreshService != null) {
        refreshService.shutdownNow();
    }

    if (refreshInterval > 0) {
        refreshService = Executors.newScheduledThreadPool(1);

        Runnable refreshCommand = new Runnable() {

            @Override
            public void run() {

                List<NikobusModule> allModules = getBindingProvider().getAllModules();

                if (allModules == null || allModules.isEmpty()) {
                    log.trace("No modules available to refresh");
                    return;
                }

                if (nextModuleToRefresh >= allModules.size()) {
                    nextModuleToRefresh = 0;
                }

                NikobusModule m = allModules.get(nextModuleToRefresh);

                log.trace("Requesting scheduled status update for {}", m.getAddress());
                NikobusCommand cmd = m.getStatusRequestCommand();
                cmd.setWaitForSilence(true);
                try {
                    sendCommand(cmd);
                } catch (Exception e) {
                    log.error("Error occurred during scheduled status refresh.", e);
                }
                nextModuleToRefresh++;
            }

        };

        // don't start the scheduler too soon, otherwise the connection may
        // not be available yet on slower systems like a pi
        refreshService.scheduleAtFixedRate(refreshCommand, 600, refreshInterval, TimeUnit.SECONDS);
        log.debug("Refresh service started. Will refresh a module every {} seconds.", refreshInterval);
    }

}

From source file:com.keithcassidy.finishline.LineCrossHandler.java

private void startBeepTimer(int beepInterval) {
    //different interval - reset the timer
    if (lastBeepInterval != beepInterval) {
        stopBeepTimer();/*from ww w. j  a  v  a2s.  c om*/

        if (beepInterval > 0) {
            scheduleBeeps = Executors.newScheduledThreadPool(1);

            scheduleBeeps.scheduleAtFixedRate(new Runnable() {
                public void run() {
                    //beep
                    PlaySounds.playProximityTone(context);

                }
            }, 0, beepInterval, TimeUnit.MILLISECONDS);

        }
    }

    lastBeepInterval = beepInterval;
}

From source file:org.wso2.carbon.identity.account.suspension.notification.task.handler.AccountSuspensionNotificationHandler.java

private void startScheduler() {

    if (!Boolean.parseBoolean(
            configs.getModuleProperties().getProperty(NotificationConstants.SUSPENSION_NOTIFICATION_ENABLED))) {
        return;/*from   w  w  w  .j av  a  2  s  . co  m*/
    }

    Date notificationTriggerTime = null;
    String notificationTriggerTimeProperty = configs.getModuleProperties()
            .getProperty(NotificationConstants.SUSPENSION_NOTIFICATION_TRIGGER_TIME);

    DateFormat dateFormat = new SimpleDateFormat(NotificationConstants.TRIGGER_TIME_FORMAT);

    if (notificationTriggerTimeProperty != null) {
        try {
            notificationTriggerTime = dateFormat.parse(notificationTriggerTimeProperty);
        } catch (ParseException e) {
            log.error("Invalid Date format for Notification trigger time", e);
        }
    }

    long schedulerDelayInSeconds = TimeUnit.HOURS.toSeconds(NotificationConstants.SCHEDULER_DELAY);

    Calendar currentTime = Calendar.getInstance();
    Calendar triggerTime = Calendar.getInstance();
    // If notificationTriggerTimeProperty is not found or not in right format default to 20:00:00.
    // In Calender.HOUR_OF_DAY (i.e. in 24-hour clock) it is 20.
    if (notificationTriggerTime != null) {
        triggerTime.setTime(notificationTriggerTime);
    } else {
        triggerTime.set(Calendar.HOUR_OF_DAY, 20);
        triggerTime.set(Calendar.MINUTE, 0);
        triggerTime.set(Calendar.SECOND, 0);
    }

    // Convert times into seconds
    long currentSecond = (currentTime.get(Calendar.HOUR_OF_DAY) * 3600) + currentTime.get(Calendar.MINUTE) * 60
            + currentTime.get(Calendar.SECOND);
    long triggerSecond = (triggerTime.get(Calendar.HOUR_OF_DAY) * 3600) + triggerTime.get(Calendar.MINUTE) * 60
            + triggerTime.get(Calendar.SECOND);
    long delay = triggerSecond - currentSecond;
    // If the notification time has passed, schedule the next day
    if (delay < 0) {
        delay += schedulerDelayInSeconds;
    }

    ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(
            NotificationTaskDataHolder.getInstance().getNotificationSendingThreadPoolSize());
    scheduler.scheduleAtFixedRate(new AccountValidatorThread(), delay, schedulerDelayInSeconds,
            TimeUnit.SECONDS);
}

From source file:fr.tpt.atlanalyser.examples.ExampleRunner.java

public void executePost2Pre(File postFile, int maxNumRuleIterations) throws IOException {
    // checkDirs();
    inputMM = getInputMMEPkg();//  w  ww  .j ava  2 s .co m
    outputMM = getOutputMMEPkg();
    makeAbstractClassesInstantiable(inputMM);
    makeAbstractClassesInstantiable(outputMM);
    Module transfo = loadHenshinTransformation();

    EcoreUtil.resolveAll(transfo);

    EPackage traceMM = resourceSet.getPackageRegistry().getEPackage("http://traces/1.0");

    stripFromAttributes(transfo);

    Resource postRes = resourceSet.getResource(URI.createFileURI(postFile.getCanonicalPath()), true);
    Module postModule = (Module) postRes.getContents().get(0);
    EList<Unit> units = postModule.getUnits();
    List<Formula> postconditions = Lists.transform(units, new Function<Unit, Formula>() {
        @Override
        public Formula apply(Unit arg0) {
            return ((Rule) arg0).getLhs().getFormula();
        }
    });

    Module preModule = HenshinFactory.eINSTANCE.createModule();
    preModule.setName("Preconditions");

    LOGGER.info("Starting Post2Pre for {}", transfo.getName());

    Post2Pre4ATL post2Pre = new Post2Pre4ATL(transfo, inputMM, outputMM, traceMM, jobs);

    ScheduledExecutorService memMonitorExecutor = Executors.newScheduledThreadPool(1);
    memMonitorExecutor.scheduleAtFixedRate(new Runnable() {

        private final MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
        private final Logger LOGGER = LogManager.getLogger("MemMon");

        @Override
        public void run() {
            // LOGGER.setAdditivity(false);

            // for (Enumeration iterator =
            // AGGWrapper.LOGGER.getAllAppenders(); iterator
            // .hasMoreElements();) {
            // Appender appender = (Appender) iterator.nextElement();
            // LOGGER.addAppender(appender);
            // }

            MemoryUsage heapUsage = memoryBean.getHeapMemoryUsage();
            final long used = heapUsage.getUsed();
            double usedGB = (double) used / (1 << 30);
            final long max = heapUsage.getMax();
            double maxGB = (double) max / (1 << 30);
            LOGGER.info(String.format("Memory use : %6.3fGB of %6.3fGB (%.2f%%)", usedGB, maxGB,
                    (float) used / max * 100));
        }
    }, 0, 10, TimeUnit.SECONDS);

    try {
        for (Formula formula : postconditions) {
            Formula pre = post2Pre.post2Pre(formula, maxNumRuleIterations);
            Rule preRule = HenshinFactory.eINSTANCE.createRule();
            Graph preLhs = HenshinFactory.eINSTANCE.createGraph();
            preLhs.setFormula(EcoreUtil.copy(pre));
            preRule.setLhs(preLhs);
            preModule.getUnits().add(preRule);
        }
    } finally {
        memMonitorExecutor.shutdown();
    }

    File outputDir = new File(baseDir, "Preconditions");
    if (!outputDir.isDirectory()) {
        outputDir.mkdir();
    }

    Resource outputRes = resourceSet
            .createResource(URI.createFileURI("Preconditions/" + postFile.getName() + "_pre.henshin"));

    outputRes.getContents().add(preModule);

    LOGGER.info("Writing Precondition in {}", outputRes.getURI().toString());
    outputRes.save(xmiSaveOptions);

    LOGGER.info("Done!");
}

From source file:com.barchart.http.server.TestHttpServer.java

@Test
public void testShutdown() throws Exception {

    final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

    final AtomicBoolean pass = new AtomicBoolean(false);

    executor.schedule(new Runnable() {

        @Override/* w  w  w .  j  a v a2  s .  c  om*/
        public void run() {

            try {
                server.shutdown().sync();
            } catch (final InterruptedException e1) {
                e1.printStackTrace();
            }

            try {
                client.execute(new HttpGet("http://localhost:" + port + "/basic"));
            } catch (final HttpHostConnectException hhce) {
                pass.set(true);
            } catch (final Exception e) {
                e.printStackTrace();
            }

        }

    }, 1000, TimeUnit.MILLISECONDS);

    final HttpGet get = new HttpGet("http://localhost:" + port + "/client-disconnect");
    final HttpResponse response = client.execute(get);
    assertEquals(200, response.getStatusLine().getStatusCode());
    // assertTrue(pass.get());

}