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:com.flipkart.phantom.runtime.impl.hystrix.HystrixMetricsAggregator.java

@Override
public void afterPropertiesSet() throws Exception {
    if (frequency > 1) {
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
        metricsSnapshotReporter = new MetricsSnapshotReporterWithAggregation(frequency);
        scheduler.scheduleAtFixedRate((Runnable) metricsSnapshotReporter, 10, 10, TimeUnit.SECONDS);
    } else {//from w ww . java  2 s.  c o  m
        metricsSnapshotReporter = new MetricsSnapshotReporterDefault();
    }
}

From source file:cherry.foundation.mail.SendMailBatchTest.java

@Test
public void testNormal() throws Exception {

    final File shutdownTrigger = new File("./shutdownTrigger.txt");
    shutdownTrigger.deleteOnExit();//from w w  w. j av a 2  s  .com
    Callable<Boolean> callable = new Callable<Boolean>() {
        @Override
        public Boolean call() {
            try (FileOutputStream os = new FileOutputStream(shutdownTrigger)) {
                return true;
            } catch (IOException ex) {
                return false;
            }
        }
    };

    ScheduledExecutorService service = Executors.newScheduledThreadPool(1);
    ScheduledFuture<Boolean> future = service.schedule(callable, 5L, TimeUnit.SECONDS);

    SendMailBatch batch = create(1000L, shutdownTrigger, false);
    ExitStatus status = batch.execute();

    assertEquals(ExitStatus.NORMAL, status);
    assertTrue(future.get().booleanValue());
    assertFalse(shutdownTrigger.exists());

    verify(bizDateTime, atLeastOnce()).now();
    verify(mailSendHandler, atLeastOnce()).listMessage((LocalDateTime) eq(null));
    verify(mailSendHandler, atLeastOnce()).sendMessage(eq(1L));
    verify(mailSendHandler, atLeastOnce()).sendMessage(eq(2L));
    verify(mailSendHandler, atLeastOnce()).sendMessage(eq(3L));
}

From source file:corner.cache.services.impl.local.LocalCacheImpl.java

@SuppressWarnings("unchecked")
private void init() {
    cache = new ConcurrentHashMap();

    expiryCache = new ConcurrentHashMap<String, Long>();

    scheduleService = Executors.newScheduledThreadPool(1);

    scheduleService.scheduleAtFixedRate(new CheckOutOfDateSchedule(cache, expiryCache), 0, expiryInterval * 60,
            TimeUnit.SECONDS);// www. j  a  v  a 2 s.c  o m

    if (logger.isInfoEnabled())
        logger.info("DefaultCache CheckService is start!");
}

From source file:interactivespaces.util.web.HttpClientHttpContentCopierTest.java

@Before
public void setup() {
    log = new Jdk14Logger("goober"); // Mockito.mock(Log.class);

    threadPool = Executors.newScheduledThreadPool(100);

    copier = new HttpClientHttpContentCopier();
    copier.startup();/*from  w  w  w  . j a v a  2s  .c o m*/

    webServerPort = 10031;
    webServerUriPrefix = "websockettest";
    webServer = new NettyWebServer(threadPool, log);
    webServer.setServerName("test-server");
    webServer.setPort(webServerPort);
    webServer.addDynamicContentHandler("/" + webServerUriPrefix, true, new HttpDynamicRequestHandler() {

        @Override
        public void handle(HttpRequest request, HttpResponse response) {
            String path = request.getUri().getPath();

            if (path.endsWith("/error")) {
                response.setResponseCode(HttpResponseCode.FORBIDDEN);
            } else {
                try {
                    response.getOutputStream().write(TEST_CONTENT.getBytes());
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    });

    webServer.startup();
}

From source file:org.apache.synapse.transport.certificatevalidation.cache.CacheManager.java

/**
 * A new cacheManager will be started on the given ManageableCache object.
 *
 * @param cache        a Manageable Cache which could be managed by this cache manager.
 * @param cacheMaxSize Maximum size of the cache. If the cache exceeds this size, LRU values will be
 *                     removed//from w  ww.  ja  v  a 2 s.c om
 */
public CacheManager(ManageableCache cache, int cacheMaxSize, int delay) {
    int NUM_THREADS = 1;
    scheduler = Executors.newScheduledThreadPool(NUM_THREADS);
    this.cache = cache;
    this.cacheMaxSize = cacheMaxSize;
    this.cacheManagingTask = new CacheManagingTask();
    this.delay = delay;
    start();
}

From source file:io.smartspaces.service.comm.network.NettyUdpSocketTest.java

@Before
public void setup() {
    log = new StandardExtendedLog("goober", new Jdk14Logger("goober"));

    threadPool = Executors.newScheduledThreadPool(100);

    SimpleSmartSpacesEnvironment spaceEnvironment = new SimpleSmartSpacesEnvironment();
    spaceEnvironment.setExecutorService(threadPool);

    clientService = new NettyUdpClientNetworkCommunicationEndpointService();
    clientService.setSpaceEnvironment(spaceEnvironment);
    clientService.startup();//from  w  ww  .  j  a v  a 2  s .  co  m

    serverService = new NettyUdpServerNetworkCommunicationEndpointService();
    serverService.setSpaceEnvironment(spaceEnvironment);
    serverService.startup();
}

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

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

From source file:com.meltmedia.dropwizard.etcd.example.EtcdExampleApplication.java

@Override
public void initialize(Bootstrap<EtcdExampleConfiguration> bootstrap) {
    executor = Executors.newScheduledThreadPool(10);

    // provides a client to the application.
    bootstrap.addBundle(etcdBundle = EtcdBundle.<EtcdExampleConfiguration>builder()
            .withConfiguration(EtcdExampleConfiguration::getEtcd).build());

    // provides access to Etcd as a JSON store using Jackson.
    // requires the client bundle to operate.
    bootstrap.addBundle(etcdJsonBundle = EtcdJsonBundle.<EtcdExampleConfiguration>builder()
            .withClient(etcdBundle::getClient).withDirectory(EtcdExampleConfiguration::getEtcdDirectory)
            .withExecutor(() -> executor).build());

    // provides services for clustering jobs with Etcd.
    // requires the JSON bundle to operate.
    bootstrap.addBundle(etcdClusterBundle = ClusterBundle.<EtcdExampleConfiguration>builder()
            .withExecutorSupplier(() -> executor).withFactorySupplier(etcdJsonBundle::getFactory).build());

    GuiceBundle.Builder<EtcdExampleConfiguration> builder = GuiceBundle.<EtcdExampleConfiguration>newBuilder()
            .setConfigClass(EtcdExampleConfiguration.class).enableAutoConfig(getClass().getPackage().getName());

    // these Guice modules provide injections for the etcd bundles.
    builder.addModule(new EtcdModule(etcdBundle));
    builder.addModule(new EtcdJsonModule(etcdJsonBundle));
    builder.addModule(new ClusterModule(etcdClusterBundle));

    builder.addModule(new EtcdExampleModule());

    bootstrap.addBundle(guiceBundle = builder.build(Stage.DEVELOPMENT));

    bootstrap.addCommand(new Commands.AddCommand());
    bootstrap.addCommand(new Commands.RemoveCommand());
    bootstrap.addCommand(new Commands.ListCommand());
}

From source file:org.gss_project.gss.server.ejb.TransactionHelper.java

/**
 * Execute the supplied command until it completes, ignoring transaction
 * rollbacks. Try at least TRANSACTION_RETRIES times before giving up,
 * each time waiting a random amount of time, using an exponential
 * backoff scheme. See http://en.wikipedia.org/wiki/Exponential_backoff
 * for the basic idea.//from  www  . ja v  a2 s .c  o  m
 *
 * @param command the command to execute
 * @return the value returned by the command
 * @throws Exception any other exception thrown by the command
 */
public T tryExecute(final Callable<T> command) throws Exception {
    T returnValue = null;
    // Schedule a Future task to call the command after delay milliseconds.
    int delay = 0;
    ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
    for (int i = 0; i < TRANSACTION_RETRIES; i++) {
        final int retry = i;
        ScheduledFuture<T> future = executor.schedule(new Callable<T>() {

            @Override
            public T call() throws Exception {
                return command.call();
            }
        }, delay, TimeUnit.MILLISECONDS);

        try {
            returnValue = future.get();
            break;
        } catch (ExecutionException e) {
            Throwable cause = e.getCause();
            if (!(cause instanceof EJBTransactionRolledbackException) || retry == TRANSACTION_RETRIES - 1) {
                logger.info("Transaction retry #" + (i + 1) + " failed due to " + cause);
                executor.shutdownNow();
                if (cause instanceof Exception)
                    throw (Exception) cause;
                if (cause instanceof Error)
                    throw (Error) cause;
            }
            delay = MIN_TIMEOUT + (int) (MIN_TIMEOUT * Math.random() * (i + 1));
            String origCause = cause.getCause() == null ? cause.getClass().getName()
                    : cause.getCause().getClass().getName();
            logger.info(
                    "Transaction retry #" + (i + 1) + " scheduled in " + delay + " msec due to " + origCause);
        }

    }
    executor.shutdownNow();
    return returnValue;
}

From source file:org.apache.hadoop.yarn.server.applicationhistoryservice.metrics.loadsimulator.jmetertest.jmetertest.AMSJMeterLoadTest.java

public AMSJMeterLoadTest(String testType, String userDefinedPropertiesFile) {

    if (null == userDefinedPropertiesFile || userDefinedPropertiesFile.isEmpty()) {
        this.amsJmeterProperties = readProperties(PROPERTIES_FILE);
    } else {// w w w .j a va  2 s  .c om
        this.amsJmeterProperties = readProperties(userDefinedPropertiesFile);
    }

    if ("U".equals(testType)) { //GET metrics simulator
        int numInstances = Integer.valueOf(amsJmeterProperties.getProperty("num-ui-instances"));
        this.scheduledExecutorService = Executors.newScheduledThreadPool(numInstances);
        this.appGetMetrics = initializeGetMetricsPayload(amsJmeterProperties);
        this.runTest(numInstances);
    } else { //PUT Metrics simulator
        Map<String, String> mapArgs = new HashMap<String, String>();
        mapArgs.put("hostName", amsJmeterProperties.getProperty("host-prefix"));
        mapArgs.put("numberOfHosts", amsJmeterProperties.getProperty("num-hosts"));
        mapArgs.put("metricsHostName", amsJmeterProperties.getProperty("ams-host-port"));
        mapArgs.put("collectInterval", amsJmeterProperties.getProperty("collection-interval"));
        mapArgs.put("sendInterval", amsJmeterProperties.getProperty("send-interval"));
        mapArgs.put("master", amsJmeterProperties.getProperty("create-master"));
        MetricsLoadSimulator.startTest(mapArgs);
    }
}