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.openhie.openempi.context.Context.java

public static void startup() {
    if (isInitialized) {
        return;//from   ww w. ja  v a  2s.  c o  m
    }
    try {
        applicationContext = new ClassPathXmlApplicationContext(getConfigLocationsAsArray());
        applicationContext.getBean("context");
        configuration.init();
        threadPool = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
        scheduler = Executors.newScheduledThreadPool(SCHEDULER_THREAD_POOL_SIZE);
        startBlockingService();
        startMatchingService();
        startNotificationService();
        startScheduledTasks();
        isInitialized = true;
    } catch (Throwable t) {
        log.error("Failed while setting up the context for OpenEMPI: " + t, t);
    }
}

From source file:com.baifendian.swordfish.execserver.ExecThriftServer.java

/**
 * @throws UnknownHostException//from  w  w w  .  jav  a 2  s. c om
 * @throws TTransportException
 */
public void run() throws UnknownHostException, TTransportException, InterruptedException {
    HdfsClient.init(ConfigurationUtil.getConfiguration());

    logger.info("register to master {}:{}", masterServer.getHost(), masterServer.getPort());

    //  master
    boolean ret = masterClient.registerExecutor(host, port, System.currentTimeMillis());
    if (!ret) {
        // ?, ?
        Thread.sleep(3000);

        ret = masterClient.registerExecutor(host, port, System.currentTimeMillis());

        if (!ret) {
            logger.error("register to master {}:{} failed", masterServer.getHost(), masterServer.getPort());
            throw new RuntimeException("register executor error");
        }
    }

    // 
    heartBeatInterval = conf.getInt(Constants.EXECUTOR_HEARTBEAT_INTERVAL,
            Constants.defaultExecutorHeartbeatInterval);

    heartbeatExecutorService = Executors.newScheduledThreadPool(Constants.defaultExecutorHeartbeatThreadNum);

    Runnable heartBeatThread = getHeartBeatThread();
    heartbeatExecutorService.scheduleAtFixedRate(heartBeatThread, 10, heartBeatInterval, TimeUnit.SECONDS);

    // ? worker service
    TProtocolFactory protocolFactory = new TBinaryProtocol.Factory();
    TTransportFactory tTransportFactory = new TTransportFactory();

    workerService = new ExecServiceImpl(host, port, conf);

    TProcessor tProcessor = new WorkerService.Processor(workerService);
    inetSocketAddress = new InetSocketAddress(host, port);
    server = getTThreadPoolServer(protocolFactory, tProcessor, tTransportFactory, inetSocketAddress,
            Constants.defaultServerMinNum, Constants.defaultServerMaxNum);

    logger.info("start thrift server on port:{}", port);

    //  daemon, ??
    Thread serverThread = new TServerThread(server);
    serverThread.setDaemon(true);
    serverThread.start();

    // ?, ??
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        postProcess();

        logger.info("exec server stop");
    }));

    synchronized (this) {
        // 
        while (running.get()) {
            try {
                logger.info("wait....................");
                wait();
            } catch (InterruptedException e) {
                logger.error("error", e);
            }
        }

        postProcess();

        logger.info("exec server stop");
    }
}

From source file:com.srotya.monitoring.kafka.util.KafkaConsumerOffsetUtil.java

public void setupMonitoring() {
    ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
    executorService.scheduleAtFixedRate(new KafkaConsumerOffsetThread(), 2,
            kafkaConfiguration.getRefreshSeconds(), TimeUnit.SECONDS);
    log.info("Monitoring thread for zookeeper offsets online");
}

From source file:com.vmware.photon.controller.model.adapters.vsphere.ovf.OvfDeployer.java

public ManagedObjectReference deployOvf(URI ovfUri, ManagedObjectReference host,
        ManagedObjectReference vmFolder, String vmName, List<OvfNetworkMapping> networks,
        ManagedObjectReference datastore, List<KeyValue> ovfProps, String deploymentConfig,
        ManagedObjectReference resourcePool) throws Exception {

    String ovfDescriptor = getRetriever().retrieveAsString(ovfUri);

    OvfCreateImportSpecParams params = new OvfCreateImportSpecParams();
    params.setHostSystem(host);/*from w  w w. j  a  v  a 2 s. co m*/
    params.setLocale("US");
    params.setEntityName(vmName);

    if (deploymentConfig == null) {
        deploymentConfig = "";
    }
    params.setDeploymentOption(deploymentConfig);

    params.getNetworkMapping().addAll(networks);
    params.setDiskProvisioning(OvfCreateImportSpecParamsDiskProvisioningType.THIN.name());

    if (ovfProps != null) {
        params.getPropertyMapping().addAll(ovfProps);
    }

    ManagedObjectReference ovfManager = this.connection.getServiceContent().getOvfManager();

    OvfCreateImportSpecResult importSpecResult = getVimPort().createImportSpec(ovfManager, ovfDescriptor,
            resourcePool, datastore, params);

    if (!importSpecResult.getError().isEmpty()) {
        return VimUtils.rethrow(importSpecResult.getError().get(0));
    }

    long totalBytes = getImportSizeBytes(importSpecResult);

    ManagedObjectReference lease = getVimPort().importVApp(resourcePool, importSpecResult.getImportSpec(),
            vmFolder, host);

    LeaseProgressUpdater leaseUpdater = new LeaseProgressUpdater(this.connection, lease, totalBytes);

    GetMoRef get = new GetMoRef(this.connection);
    HttpNfcLeaseInfo httpNfcLeaseInfo;

    ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
    try {
        leaseUpdater.awaitReady();
        logger.info("Lease ready");

        // start updating the lease
        leaseUpdater.start(executorService);

        httpNfcLeaseInfo = get.entityProp(lease, PROP_INFO);

        List<HttpNfcLeaseDeviceUrl> deviceUrls = httpNfcLeaseInfo.getDeviceUrl();

        String ip = this.connection.getURI().getHost();

        String basePath = extractParentPath(ovfUri);

        for (HttpNfcLeaseDeviceUrl deviceUrl : deviceUrls) {
            String deviceKey = deviceUrl.getImportKey();

            for (OvfFileItem ovfFileItem : importSpecResult.getFileItem()) {
                if (deviceKey.equals(ovfFileItem.getDeviceId())) {
                    logger.debug("Importing device id: {}", deviceKey);
                    String sourceUri = basePath + ovfFileItem.getPath();
                    String uploadUri = makUploadUri(ip, deviceUrl);
                    uploadVmdkFile(ovfFileItem, sourceUri, uploadUri, leaseUpdater,
                            this.ovfRetriever.getClient());
                    logger.info("Completed uploading VMDK file {}", sourceUri);
                }
            }
        }

        // complete lease
        leaseUpdater.complete();
    } catch (Exception e) {
        leaseUpdater.abort(VimUtils.convertExceptionToFault(e));
        logger.info("Error importing ovf", e);
        throw e;
    } finally {
        executorService.shutdown();
    }

    httpNfcLeaseInfo = get.entityProp(lease, PROP_INFO);
    ManagedObjectReference entity = httpNfcLeaseInfo.getEntity();

    // as this is an OVF it makes sense to enable the OVF transport
    // only the guestInfo is enabled by default
    VmConfigSpec spec = new VmConfigSpec();
    spec.getOvfEnvironmentTransport().add(TRANSPORT_GUESTINFO);
    VirtualMachineConfigSpec reconfig = new VirtualMachineConfigSpec();
    reconfig.setVAppConfig(spec);

    ManagedObjectReference reconfigTask = getVimPort().reconfigVMTask(entity, reconfig);
    VimUtils.waitTaskEnd(this.connection, reconfigTask);

    return entity;
}

From source file:gov.nrel.bacnet.consumer.BACnet.java

private void initialize(Config config) throws IOException {
    LinkedBlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>(1000);
    RejectedExecutionHandler rejectedExec = new RejectedExecHandler();
    // schedule polling on single threaded service because local device instance is not threadsafe
    execSvc = Executors.newFixedThreadPool(config.getNumThreads());
    //give databus recording 2 threads to match old code
    recorderSvc = new ThreadPoolExecutor(20, 20, 120, TimeUnit.SECONDS, queue, rejectedExec);
    schedSvc = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(config.getNumThreads());
    exec = new OurExecutor(schedSvc, execSvc, recorderSvc);
    String devname = config.getNetworkDevice();
    int device_id = config.getDeviceId();
    NetworkInterface networkinterface = null;

    try {// ww  w .jav  a  2  s  .  com
        networkinterface = java.net.NetworkInterface.getByName(devname);
    } catch (Exception ex) {
        System.out.println("Unable to open device: " + devname);
        System.exit(-1);
    }

    if (networkinterface == null) {
        System.out.println("Unable to open device: " + devname);
        System.exit(-1);
    }

    List<InterfaceAddress> addresses = networkinterface.getInterfaceAddresses();

    String sbroadcast = null;
    String saddress = null;
    //InterfaceAddress ifaceaddr = null;

    for (InterfaceAddress address : addresses) {
        logger.fine("Evaluating address: " + address.toString());
        if (address.getAddress().getAddress().length == 4) {
            logger.info("Address is ipv4, selecting: " + address.toString());
            sbroadcast = address.getBroadcast().toString().substring(1);
            saddress = address.getAddress().toString().substring(1);
            //ifaceaddr = address;
            break;
        } else {
            logger.info("Address is not ipv4, not selecting: " + address.toString());
        }
    }

    logger.info("Binding to: " + saddress + " " + sbroadcast);

    localDevice = new LocalDevice(device_id, sbroadcast);
    localDevice.setPort(LocalDevice.DEFAULT_PORT);
    localDevice.setTimeout(localDevice.getTimeout() * 3);
    localDevice.setSegTimeout(localDevice.getSegTimeout() * 3);
    try {
        localDevice.initialize();
        localDevice.setRetries(0); //don't retry as it seems to really be a waste.
    } catch (IOException e) {
        e.printStackTrace();
        return;
    }

    if (config.getSlaveDeviceEnabled()) {
        slaveDeviceTimer = new Timer();
        slaveDeviceTimer.schedule(new gov.nrel.bacnet.SlaveDevice(localDevice, config), 1000,
                config.getSlaveDeviceUpdateInterval() * 1000);
    }

    int counter = 0;

    String username = config.getDatabusUserName();
    String key = config.getDatabusKey();

    logger.info("user=" + username + " key=" + key);

    DatabusSender sender = null;

    if (config.getDatabusEnabled()) {
        sender = new DatabusSender(username, key, execSvc, config.getDatabusUrl(), config.getDatabusPort(),
                true);
    }
    logger.info("databus sender: " + sender);
    writer = new DatabusDataWriter(new DataPointWriter(sender));
    logger.info("databus writer" + writer);
}

From source file:colt.nicity.performance.agent.LatentHttpPump.java

public void start() {
    ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
    scheduledExecutorService.scheduleWithFixedDelay(() -> {
        try {//from  w  w w . ja v  a 2s .c  om
            final long now = System.currentTimeMillis();
            Boolean enabled = latency.getLatentGraph(this.enabled.get()).latentDepths((from, to) -> {
                // TODO batching
                try {
                    JSONObject sample = new JSONObject();
                    sample.put("clusterName", clusterName);
                    sample.put("serviceName", serviceName);
                    sample.put("serviceVersion", serviceVersion);
                    sample.put("sampleTimestampEpochMillis", now);
                    sample.put("from", latentJson(from));
                    sample.put("to", latentJson(to));
                    HttpResponse postJson = httpClient.postJson("/profile/latents", sample.toJSONString());
                    if (postJson.getStatusCode() >= 200 && postJson.getStatusCode() < 300) {
                        String response = new String(postJson.getResponseBody());
                        return Boolean.getBoolean(response);
                    } else {
                        return null;
                    }
                } catch (Exception x) {
                    //if (verbose) {
                    //System.out.println("Latent Service is inaccessible. "+x.getMessage());
                    //}
                    return null;
                }

            });

            if (enabled != null) {
                this.enabled.set(enabled);
            }

        } catch (Throwable t) {
            t.printStackTrace();
        }
    }, 5, 5, TimeUnit.SECONDS);
}

From source file:org.akubraproject.rmi.TransactionalStoreTest.java

@Test
public void testMTStress() throws InterruptedException, ExecutionException {
    ScheduledExecutorService executor = Executors.newScheduledThreadPool(10);
    List<Future<Void>> futures = new ArrayList<Future<Void>>();

    for (int loop = 0; loop < 30; loop++) {
        futures.add(executor.submit(new Callable<Void>() {
            public Void call() throws Exception {
                for (int i = 0; i < 10; i++) {
                    doInTxn(new Action() {
                        public void run(BlobStoreConnection con) throws Exception {
                            for (int j = 0; j < 3; j++) {
                                URI id = URI.create("urn:mt:" + UUID.randomUUID());
                                byte[] buf = new byte[4096];
                                Blob b;
                                b = con.getBlob(id, null);
                                OutputStream out;
                                IOUtils.copyLarge(new ByteArrayInputStream(buf),
                                        out = b.openOutputStream(buf.length, true));
                                out.close();

                                InputStream in;
                                assertEquals(buf, IOUtils.toByteArray(in = b.openInputStream()));
                                in.close();
                                b.delete();
                            }/*ww  w.  j  av  a2 s  .  co  m*/
                        }
                    }, true);
                }
                return null;
            }
        }));
    }

    for (Future<Void> res : futures)
        res.get();
}

From source file:ln.paign10.arduinopixel.MainActivity.java

@SuppressLint("ShowToast")
@Override/*from ww w  .j  a v  a  2s.  co m*/
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mPrefs = getPreferences(MODE_PRIVATE);
    mUri[0] = mPrefs.getInt("Int4", 192);
    mUri[1] = mPrefs.getInt("Int3", 168);
    mUri[2] = mPrefs.getInt("Int2", 1);
    mUri[3] = mPrefs.getInt("Int1", 100);
    mUri[4] = mPrefs.getInt("Port", 80);

    mColorPicker = (ColorPicker) findViewById(R.id.colorPicker);

    mSwitch = (Switch) findViewById(R.id.power_switch);
    mSwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            updatePowerState(isChecked);
        }
    });

    mToast = Toast.makeText(MainActivity.this, "", Toast.LENGTH_SHORT);

    executor = Executors.newScheduledThreadPool(1);
}

From source file:ox.softeng.burst.services.BurstService.java

public BurstService(Properties properties) {

    logger.info("Starting application version {}", System.getProperty("applicationVersion"));

    // Output env version from potential dockerfile environment
    if (System.getenv("BURST_VERSION") != null)
        logger.info("Docker container build version {}", System.getenv("BURST_VERSION"));

    String user = (String) properties.get("hibernate.connection.user");
    String url = (String) properties.get("hibernate.connection.url");
    String password = (String) properties.get("hibernate.connection.password");

    logger.info("Migrating database using: \n" + "  url: {}" + "  user: {}" + "  password: ****", url, user);
    migrateDatabase(url, user, password);
    entityManagerFactory = Persistence.createEntityManagerFactory("ox.softeng.burst", properties);

    String rabbitMQHost = properties.getProperty("rabbitmq.host");
    String rabbitMQExchange = properties.getProperty("rabbitmq.exchange");
    String rabbitMQQueue = properties.getProperty("rabbitmq.queue");
    String rabbitPortStr = properties.getProperty("rabbitmq.port");
    String rabbitUser = properties.getProperty("rabbitmq.user", ConnectionFactory.DEFAULT_USER);
    String rabbitPassword = properties.getProperty("rabbitmq.password", ConnectionFactory.DEFAULT_PASS);

    Integer rabbitPort = ConnectionFactory.DEFAULT_AMQP_PORT;

    try {// w w w.ja  v  a  2 s .co m
        rabbitPort = Integer.parseInt(rabbitPortStr);
    } catch (NumberFormatException ignored) {
        logger.warn("Configuration supplied rabbit port '{}' is not numerical, using default value {}",
                rabbitPortStr, rabbitPort);
    }

    logger.info(
            "Creating new RabbitMQ Service using: \n" + "  host: {}:{}\n" + "  user: {}:{}\n"
                    + "  exchange: {}\n" + "  queue: {}",
            rabbitMQHost, rabbitPort, rabbitUser, rabbitPassword, rabbitMQExchange, rabbitMQQueue);
    try {
        rabbitReceiver = new RabbitService(rabbitMQHost, rabbitPort, rabbitUser, rabbitPassword,
                rabbitMQExchange, rabbitMQQueue, entityManagerFactory);
    } catch (IOException | TimeoutException e) {
        logger.error("Cannot create RabbitMQ service: " + e.getMessage(), e);
        System.exit(1);
    } catch (JAXBException e) {
        logger.error("Cannot create JAXB unmarshaller for messages: " + e.getMessage(), e);
        System.exit(1);
    }

    logger.info("Creating new report scheduler");
    reportScheduler = new ReportScheduler(entityManagerFactory, properties);
    scheduleFrequency = Integer
            .parseInt(properties.getProperty("report.schedule.frequency", SCHEDULE_FREQUENCY.toString()));

    logger.info("Creating new executor with thread pool size {}", THREAD_POOL_SIZE);
    executor = Executors.newScheduledThreadPool(THREAD_POOL_SIZE);
}

From source file:com.ovalsearch.services.impl.StartupServiceImpl.java

private void loadNewExecutorServiceAndScheduleTasks() {
    ScheduledExecutorService executorService = Executors.newScheduledThreadPool(CacheManager.getInstance()
            .getCache(PropertyMapCache.class).getPropertyInteger(Property.SCHEDULER_THREAD_POOL_SIZE));
    taskScheduler.setExecutorService(executorService);
    LOG.info("Scheduling Task in newly created Executor Service");
    ScheduledFuture<?> futureObject = taskScheduler.getExecutorService().scheduleAtFixedRate(
            new DownloadDataThread(
                    CacheManager.getInstance().getCache(PropertyMapCache.class)
                            .getPropertyString(Property.FILENAME),
                    CacheManager.getInstance().getCache(PropertyMapCache.class)
                            .getPropertyString(Property.REMOTE_REPO),
                    entityDao, applicationsDas),
            getInitialDelayInMinutes(), CacheManager.getInstance().getCache(PropertyMapCache.class)
                    .getPropertyInteger(Property.FILE_DOWNLOAD_PERIOD) * 60,
            TimeUnit.MINUTES);/* w w  w . j a v  a 2s.  c  o  m*/
    taskScheduler.setScheduledTask(futureObject);
}