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.cerberus.launchcampaign.checkcampaign.CheckCampaignStatus.java

/**
 * Check all 5 seconds the status of campaign's execution. 
 * @param checkCampaign call method checkCampaign() all 5 seconds with parameter {@link ResultCIDto}.  
 *                   {@link ResultCIDto} contains all information of execution of campaing at the instant t
 * @param result call method result() when campaign execution is finish.
 *             {@link ResultCIDto} contains all information of execution at finish time
 * @throws Exception //  w  w  w .  ja v a 2 s  . com
 */
public void execute(final CheckCampaignEvent checkCampaign, final ResultEvent result, final LogEvent logEvent)
        throws Exception {
    final ScheduledThreadPoolExecutor sch = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(1);

    final AtomicReference<Exception> exceptionOnThread = new AtomicReference<Exception>();

    sch.scheduleWithFixedDelay(new Runnable() {

        @Override
        public void run() {
            try {
                URL resultURL = new URL(urlCerberus + "/" + Constantes.URL_RESULT_CI + "?tag=" + tagCerberus);
                ResultCIDto resultDto = new ObjectMapper().readValue(resultURL, ResultCIDto.class);

                // condition to finish task
                if (!"PE".equals(resultDto.getResult())) {
                    result.result(resultDto);
                    sch.shutdown(); // when campaign is finish, we shutdown the schedule thread
                }

                if (!checkCampaign.checkCampaign(resultDto)) {
                    sch.shutdown();
                }
            } catch (SocketException e) {
                // do nothing during network problem. Wait the timeout to shutdown, and notify the error to logEvent
                logEvent.log("", e.getMessage() + "\n" + ExceptionUtils.getStackTrace(e));
            } catch (Exception e) {
                exceptionOnThread.set(e);
                sch.shutdown();
            }
        }
    }, 0, this.timeToRefreshCampaignStatus, TimeUnit.SECONDS);

    sch.awaitTermination(this.timeoutForCampaignExecution, TimeUnit.SECONDS);

    // pass exeption of thread to called method
    if (exceptionOnThread.get() != null) {
        throw exceptionOnThread.get();
    }
}

From source file:org.ebayopensource.scc.track.TrackerClientTest.java

@Test
public void testGet() {
    AppConfiguration config = mock(AppConfiguration.class);
    when(config.getString("trackerClient.endpoint.host")).thenReturn("127.0.0.1");
    when(config.getInt("trackerClient.endpoint.port")).thenReturn(8080);
    when(config.getString("trackerClient.endpoint.path"))
            .thenReturn("/build-service/webapi/serviceCache/tracker");
    when(config.getBoolean("trackerClient.endpoint.isSecure")).thenReturn(false);

    TrackerClient tc = new TrackerClient(config, Executors.newScheduledThreadPool(1));

    assertNotNull(tc.getIp());/*from  ww w. j a  v a  2  s.  com*/
}

From source file:org.openhab.binding.ebus.connection.EBusCommandProcessor.java

@Override
public void bindingChanged(BindingProvider provider, final String itemName) {

    logger.debug("Binding changed for item {}", itemName);

    final EBusBindingProvider eBusProvider = (EBusBindingProvider) provider;
    int refreshRate = eBusProvider.getRefreshRate(itemName);

    if (refreshRate > 0) {

        final Runnable r = new Runnable() {
            @Override//from w  w  w . j a  v a2 s.  c  o  m
            public void run() {
                byte[] data = composeSendData(eBusProvider, itemName, null);

                if (data != null && data.length > 0) {
                    if (connector == null) {
                        logger.warn("eBus connector not ready, can't send data yet!");
                    } else {
                        connector.send(data);
                    }
                } else {
                    logger.warn("No data to send for item {}! Check your item configuration.", itemName);
                }
            }
        };

        if (futureMap.containsKey(itemName)) {
            logger.debug("Stopped old polling item {} ...", itemName);
            futureMap.remove(itemName).cancel(true);
        }

        if (scheduler == null) {
            scheduler = Executors.newScheduledThreadPool(2);
        }

        logger.debug("Add polling item {} with refresh rate {} to scheduler ...", itemName, refreshRate);

        // do not start all pollings at the same time
        int randomInitDelay = (int) (Math.random() * (30 - 4) + 4);
        futureMap.put(itemName,
                scheduler.scheduleWithFixedDelay(r, randomInitDelay, refreshRate, TimeUnit.SECONDS));

    } else if (futureMap.containsKey(itemName)) {
        logger.debug("Remove scheduled refresh for item {}", itemName);
        futureMap.get(itemName).cancel(true);
        futureMap.remove(itemName);
    }
}

From source file:org.eclipse.gyrex.cloud.tests.internal.locking.DurableLockTests.java

/**
 * @throws java.lang.Exception/*from  w  w  w  . ja  v a2s  .c o m*/
 */
@Before
public void setUp() throws Exception {
    executorService = Executors.newScheduledThreadPool(4);

    // configure debug output
    CloudDebug.debug = true;
    CloudDebug.zooKeeperLockService = true;
    CloudDebug.zooKeeperGateLifecycle = false;
    CloudDebug.zooKeeperServer = false;
    CloudDebug.nodeMetrics = false;
    CloudDebug.cloudState = false;
}

From source file:org.pentaho.di.www.ge.trans.LogBrowser.java

public void installLogSniffer() {
    // Create a new buffer appender to the log and capture that directly...
    ////from w ww .j a va 2s .c  o  m
    lastLogId = new AtomicInteger(-1);
    busy = new AtomicBoolean(false);
    logLayout = new KettleLogLayout(true);

    /*
     * final StyleRange normalLogLineStyle = new StyleRange();
     * normalLogLineStyle.foreground =
     * GUIResource.getInstance().getColorBlue(); final StyleRange
     * errorLogLineStyle = new StyleRange(); errorLogLineStyle.foreground =
     * GUIResource.getInstance().getColorRed();
     */

    // Refresh the log every second or so
    //
    ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    logRefreshTimerFuture = scheduler.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            busy.set(true);
            System.out.println(String.format("Running LogDelegate refreshLog()"));
            new Thread(new Runnable() {
                public void run() {
                    collectAndPushishLog();
                }
            }).start();
            busy.set(false);
        }
    }, 1000, 500, TimeUnit.MILLISECONDS);
}

From source file:org.apache.marmotta.loader.statistics.Statistics.java

public void startSampling() {
    log.info("statistics gathering enabled; starting statistics database");

    this.start = System.currentTimeMillis();
    this.previous = System.currentTimeMillis();

    try {/*  www . j  a v a 2 s  .  co m*/
        statFile = Files.createTempFile("kiwiloader.", ".rrd");
        Path gFile;
        if (configuration.containsKey(LoaderOptions.STATISTICS_GRAPH)) {
            gFile = Paths.get(configuration.getString(LoaderOptions.STATISTICS_GRAPH));
        } else {
            gFile = Files.createTempFile("marmotta-loader.", ".png");
        }

        RrdDef stCfg = new RrdDef(statFile.toString());
        stCfg.setStep(SAMPLE_INTERVAL);
        stCfg.addDatasource("triples", DsType.COUNTER, 600, Double.NaN, Double.NaN);
        stCfg.addArchive(ConsolFun.AVERAGE, 0.5, 1, 1440); // every five seconds for 2 hours
        stCfg.addArchive(ConsolFun.AVERAGE, 0.5, 12, 1440); // every minute for 1 day
        stCfg.addArchive(ConsolFun.AVERAGE, 0.5, 60, 1440); // every five minutes for five days

        statDB = new RrdDb(stCfg);
        statSample = statDB.createSample();
        statLastDump = System.currentTimeMillis();

        // start a sampler thread to run at the SAMPLE_INTERVAL
        statSampler = Executors.newScheduledThreadPool(2);
        statSampler.scheduleAtFixedRate(new StatisticsUpdater(), 0, SAMPLE_INTERVAL, TimeUnit.SECONDS);

        // create a statistics diagram every 5 minutes
        diagramUpdater = new DiagramUpdater(gFile);
        statSampler.scheduleAtFixedRate(diagramUpdater, DIAGRAM_INTERVAL, DIAGRAM_INTERVAL, TimeUnit.SECONDS);
    } catch (IOException e) {
        log.warn("could not initialize statistics database: {}", e.getMessage());
    }

}

From source file:org.apache.nifi.io.nio.ChannelListener.java

public ChannelListener(final int threadPoolSize, final StreamConsumerFactory consumerFactory,
        final BufferPool bufferPool, int timeout, TimeUnit unit, final boolean readSingleDatagram)
        throws IOException {
    this.executor = Executors.newScheduledThreadPool(threadPoolSize + 1); // need to allow for long running ChannelDispatcher thread
    this.serverSocketSelector = Selector.open();
    this.socketChannelSelector = Selector.open();
    this.bufferPool = bufferPool;
    this.initialBufferPoolSize = bufferPool.size();
    channelDispatcher = new ChannelDispatcher(serverSocketSelector, socketChannelSelector, executor,
            consumerFactory, bufferPool, timeout, unit, readSingleDatagram);
    executor.schedule(channelDispatcher, 50, TimeUnit.MILLISECONDS);
}

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

public void calculate() {

    Runnable helloRunnable = new Runnable() {
        public void run() {
            System.out.println(messageCount);
            messageCount = 0;/*from ww w.ja  va  2 s  .co  m*/
        }
    };

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

}

From source file:com.mobius.software.mqtt.performance.controller.Controller.java

private void initTaskExecutor() {
    scheduler = new PeriodicQueuedTasks<TimedTask>(Config.getInstance().getTimersInterval(), mainQueue);
    workersExecutor = Executors.newFixedThreadPool(Config.getInstance().getWorkers());
    for (int i = 0; i < Config.getInstance().getWorkers(); i++) {
        Worker worker = new Worker(scheduler, mainQueue);
        workers.add(worker);//  w ww.j a va  2s .  c  o m
        workersExecutor.submit(worker);
    }
    timersExecutor = Executors.newScheduledThreadPool(2);
    timersExecutor.scheduleAtFixedRate(new PeriodicTasksRunner(scheduler), 0,
            Config.getInstance().getTimersInterval(), TimeUnit.MILLISECONDS);

}

From source file:biospectra.classify.ClassifierClient.java

public ClassifierClient(ClientConfiguration conf) throws Exception {
    if (conf == null) {
        throw new IllegalArgumentException("conf is null");
    }//w  w w . ja v a2s .  c  om

    this.conf = conf;

    for (int i = 0; i < conf.getRabbitMQHostnames().size(); i++) {

        RabbitMQInputClient.RabbitMQInputClientEventHandler handler = new RabbitMQInputClient.RabbitMQInputClientEventHandler() {
            @Override
            public void onSuccess(long reqId, String header, String sequence, List<SearchResultEntry> result,
                    ClassificationResult.ClassificationResultType type, String taxonRank, String taxonName) {
                if (responseHandler != null) {
                    responseHandler.onSuccess(reqId, header, sequence, result, type, taxonRank, taxonName);
                } else {
                    LOG.error("responseHandler is not set");
                }
            }

            @Override
            public void onTimeout(long reqId, String header, String sequence) {
                RabbitMQInputClient client = this.getClient();
                client.reportTimeout();

                if (responseHandler != null) {
                    responseHandler.onTimeout(reqId, header, sequence);
                } else {
                    LOG.error("responseHandler is not set");
                }
            }
        };

        RabbitMQInputClient client = new RabbitMQInputClient(conf, i, handler);
        this.clients.add(client);
    }

    this.retransmitThreadPool = Executors.newScheduledThreadPool(4);
}