Example usage for java.util.concurrent Executors newSingleThreadScheduledExecutor

List of usage examples for java.util.concurrent Executors newSingleThreadScheduledExecutor

Introduction

In this page you can find the example usage for java.util.concurrent Executors newSingleThreadScheduledExecutor.

Prototype

public static ScheduledExecutorService newSingleThreadScheduledExecutor() 

Source Link

Document

Creates a single-threaded executor that can schedule commands to run after a given delay, or to execute periodically.

Usage

From source file:org.codice.ddf.spatial.ogc.wfs.v1_0_0.catalog.source.WfsSource.java

public WfsSource() {
    // Required for bean creation
    scheduler = Executors.newSingleThreadScheduledExecutor();
}

From source file:com.hurence.logisland.connect.opc.ua.OpcUaSourceTaskTest.java

@Test
@Ignore//from w  w w .  j ava2 s . c om
public void e2eTest() throws Exception {
    OpcUaSourceConnector connector = new OpcUaSourceConnector();
    Map<String, String> properties = new HashMap<>();
    properties.put(OpcUaSourceConnector.PROPERTY_AUTH_BASIC_USER, "test");
    properties.put(OpcUaSourceConnector.PROPERTY_AUTH_BASIC_PASSWORD, "test");
    properties.put(CommonDefinitions.PROPERTY_CONNECTION_SOCKET_TIMEOUT, "10000");
    properties.put(CommonDefinitions.PROPERTY_SERVER_URI, "opc.tcp://127.0.0.1:53530/OPCUA/SimulationServer");
    properties.put(CommonDefinitions.PROPERTY_TAGS_ID, "ns=5;s=Counter1,ns=5;s=Random1,ns=5;s=Sinusoid1");
    properties.put(CommonDefinitions.PROPERTY_TAGS_STREAM_MODE, "SUBSCRIBE,POLL,SUBSCRIBE");
    properties.put(CommonDefinitions.PROPERTY_TAGS_SAMPLING_RATE, "PT3S,PT0.01S,PT1S");
    properties.put(OpcUaSourceConnector.PROPERTY_DATA_PUBLICATION_RATE, "PT1S");

    connector.start(properties);
    OpcUaSourceTask task = new OpcUaSourceTask();
    task.start(connector.taskConfigs(1).get(0));
    ScheduledExecutorService es = Executors.newSingleThreadScheduledExecutor();
    Gson json = new Gson();
    es.scheduleAtFixedRate(() -> {
        try {
            task.poll().stream()
                    .map(a -> Pair.of(new Date((Long) a.sourceOffset().get(OpcRecordFields.SAMPLED_TIMESTAMP)),
                            json.toJson(a)))
                    .forEach(System.out::println);
        } catch (InterruptedException e) {
            //do nothing
        }
    }, 0, 10, TimeUnit.MILLISECONDS);

    Thread.sleep(600000);
    task.stop();
    es.shutdown();
    connector.stop();
}

From source file:org.apache.hama.bsp.SimpleTaskScheduler.java

public SimpleTaskScheduler() {
    this.jobListener = new JobListener();
    this.jobProcessor = new JobProcessor();
    this.scheduler = Executors.newSingleThreadScheduledExecutor();
}

From source file:org.dcm4che3.tool.dcmqrscp.DcmQRSCP.java

public static void main(String[] args) {
    try {//from   ww  w .j av a2 s  .c  om
        CommandLine cl = parseComandLine(args);
        DcmQRSCP<InstanceLocator> main = new DcmQRSCP<InstanceLocator>();
        main.init();
        CLIUtils.configure(main.fsInfo, cl);
        CLIUtils.configureBindServer(main.conn, main.ae, cl);
        CLIUtils.configure(main.conn, cl);
        configureDicomFileSet(main, cl);
        configureTransferCapability(main, cl);
        configureInstanceAvailability(main, cl);
        configureStgCmt(main, cl);
        configureSendPending(main, cl);
        configureRemoteConnections(main, cl);
        ExecutorService executorService = Executors.newCachedThreadPool();
        ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        main.device.setScheduledExecutor(scheduledExecutorService);
        main.device.setExecutor(executorService);
        main.device.bindConnections();
    } catch (ParseException e) {
        System.err.println("dcmqrscp: " + e.getMessage());
        System.err.println(rb.getString("try"));
        System.exit(2);
    } catch (Exception e) {
        System.err.println("dcmqrscp: " + e.getMessage());
        e.printStackTrace();
        System.exit(2);
    }
}

From source file:at.wada811.android.library.demos.concurrent.ExecutorActivity.java

/**
 * {@link ScheduledExecutorService#scheduleAtFixedRate(Runnable, long, long, TimeUnit)}
 * ????//from   w w  w  . java2 s. c om
 * 
 * <p>
 * ????????????????????? <br>
 * ??????????????????
 * </p>
 */
public void newSingleThreadScheduledExecutorAtFixedRateDuringExecutionTest() {
    LogUtils.d();
    ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
    executorService.scheduleAtFixedRate(new ExecutorRunnable("A", 3), 1, 2, TimeUnit.SECONDS);
    shutdown(executorService);
}

From source file:org.codice.ddf.commands.catalog.IngestCommand.java

@Override
protected Object executeWithSubject() throws Exception {

    final CatalogFacade catalog = getCatalog();
    final File inputFile = new File(filePath);

    if (!inputFile.exists()) {
        printErrorMessage("File or directory [" + filePath + "] must exist.");
        console.println("If the file does indeed exist, try putting the path in quotes.");
        return null;
    }//from   w ww .  j a  v a 2  s  . com

    if (deprecatedBatchSize != DEFAULT_BATCH_SIZE) {
        // user specified the old style batch size, so use that
        printErrorMessage(
                "Batch size positional argument is DEPRECATED, please use --batchsize option instead.");
        batchSize = deprecatedBatchSize;
    }

    if (batchSize <= 0) {
        printErrorMessage(
                "A batch size of [" + batchSize + "] was supplied. Batch size must be greater than 0.");
        return null;
    }

    if (!StringUtils.isEmpty(failedDir)) {
        failedIngestDirectory = new File(failedDir);
        if (!verifyFailedIngestDirectory()) {
            return null;
        }

        /**
         * Batch size is always set to 1, when using an Ingest Failure Directory.  If a batch size is specified by the user, issue 
         * a warning stating that a batch size of 1 will be used.
         */
        if (batchSize != DEFAULT_BATCH_SIZE) {
            console.println("WARNING: An ingest failure directory was supplied in addition to a batch size of "
                    + batchSize
                    + ". When using an ingest failure directory, the batch size must be 1. Setting batch size to 1.");
        }

        batchSize = 1;
    }

    BundleContext bundleContext = getBundleContext();
    if (!DEFAULT_TRANSFORMER_ID.equals(transformerId)) {
        ServiceReference[] refs = null;

        try {
            refs = bundleContext.getServiceReferences(InputTransformer.class.getName(),
                    "(|" + "(" + Constants.SERVICE_ID + "=" + transformerId + ")" + ")");
        } catch (InvalidSyntaxException e) {
            throw new IllegalArgumentException("Invalid transformer transformerId: " + transformerId, e);
        }

        if (refs == null || refs.length == 0) {
            throw new IllegalArgumentException("Transformer " + transformerId + " not found");
        } else {
            transformer = (InputTransformer) bundleContext.getService(refs[0]);
        }
    }

    Stream<Path> ingestStream = Files.walk(inputFile.toPath(), FileVisitOption.FOLLOW_LINKS);

    int totalFiles = (inputFile.isDirectory()) ? inputFile.list().length : 1;
    fileCount.getAndSet(totalFiles);

    final ArrayBlockingQueue<Metacard> metacardQueue = new ArrayBlockingQueue<>(batchSize * multithreaded);

    ExecutorService queueExecutor = Executors.newSingleThreadExecutor();

    final long start = System.currentTimeMillis();

    printProgressAndFlush(start, fileCount.get(), 0);

    queueExecutor.submit(() -> buildQueue(ingestStream, metacardQueue, start));

    final ScheduledExecutorService batchScheduler = Executors.newSingleThreadScheduledExecutor();

    BlockingQueue<Runnable> blockingQueue = new ArrayBlockingQueue<>(multithreaded);
    RejectedExecutionHandler rejectedExecutionHandler = new ThreadPoolExecutor.CallerRunsPolicy();
    ExecutorService executorService = new ThreadPoolExecutor(multithreaded, multithreaded, 0L,
            TimeUnit.MILLISECONDS, blockingQueue, rejectedExecutionHandler);

    submitToCatalog(batchScheduler, executorService, metacardQueue, catalog, start);

    while (!doneBuildingQueue.get() || processingThreads.get() != 0) {
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            LOGGER.error("Ingest 'Waiting for processing to finish' thread interrupted: {}", e);
        }
    }

    try {
        queueExecutor.shutdown();
        executorService.shutdown();
        batchScheduler.shutdown();
    } catch (SecurityException e) {
        LOGGER.error("Executor service shutdown was not permitted: {}", e);
    }

    printProgressAndFlush(start, fileCount.get(), ingestCount.get() + ignoreCount.get());
    long end = System.currentTimeMillis();
    console.println();
    String elapsedTime = timeFormatter.print(new Period(start, end).withMillis(0));

    console.println();
    console.printf(" %d file(s) ingested in %s %n", ingestCount.get(), elapsedTime);

    LOGGER.info("{} file(s) ingested in {} [{} records/sec]", ingestCount.get(), elapsedTime,
            calculateRecordsPerSecond(ingestCount.get(), start, end));
    INGEST_LOGGER.info("{} file(s) ingested in {} [{} records/sec]", ingestCount.get(), elapsedTime,
            calculateRecordsPerSecond(ingestCount.get(), start, end));

    if (fileCount.get() != ingestCount.get()) {
        console.println();
        if ((fileCount.get() - ingestCount.get() - ignoreCount.get()) >= 1) {
            String failedAmount = Integer.toString(fileCount.get() - ingestCount.get() - ignoreCount.get());
            printErrorMessage(
                    failedAmount + " file(s) failed to be ingested.  See the ingest log for more details.");
            INGEST_LOGGER.warn("{} files(s) failed to be ingested.", failedAmount);
        }
        if (ignoreList != null) {
            String ignoredAmount = Integer.toString(ignoreCount.get());
            printColor(Ansi.Color.YELLOW,
                    ignoredAmount + " file(s) ignored.  See the ingest log for more details.");
            INGEST_LOGGER.warn("{} files(s) were ignored.", ignoredAmount);
        }
    }
    console.println();

    return null;
}

From source file:org.dcm4che3.tool.syslog.Syslog.java

public void init() {
    remote.setTlsProtocols(conn.getTlsProtocols());
    remote.setTlsCipherSuites(conn.getTlsCipherSuites());
    logDevice.setScheduledExecutor(Executors.newSingleThreadScheduledExecutor());
    auditLogger.sendQueuedMessages();/*from  w  w  w.  j  a va2s. com*/
}

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  w  w . j  a va2s. co  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:org.wso2.carbon.device.mgt.etc.controlqueue.mqtt.MqttSubscriber.java

/**
 * Callback method which is triggered once the MQTT client losers its connection to the broker.
 * A scheduler thread is spawned to continuously re-attempt and connect to the broker and
 * subscribe to the device's topic. This thread is scheduled to execute after every break
 * equal to that of the 'reConnectionInterval' of the MQTTClient.
 *
 * @param throwable a Throwable Object containing the details as to why the failure occurred.
 *///w  ww .  j  a  v a2  s. c  o m
@Override
public void connectionLost(Throwable throwable) {
    log.warn("Lost Connection for client: " + this.clientId + " to " + this.mqttBrokerEndPoint
            + ".\nThis was due to - " + throwable.getMessage());

    Runnable reSubscriber = new Runnable() {
        @Override
        public void run() {
            if (!isConnected()) {
                if (log.isDebugEnabled()) {
                    log.debug("Subscriber reconnecting to queue........");
                }
                try {
                    connectAndSubscribe();
                } catch (DeviceManagementException e) {
                    if (log.isDebugEnabled()) {
                        log.debug("Could not reconnect and subscribe to ControlQueue.");
                    }
                }
            } else {
                return;
            }
        }
    };

    ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
    service.scheduleAtFixedRate(reSubscriber, 0, this.reConnectionInterval, TimeUnit.SECONDS);
}

From source file:org.igov.service.business.dfs.DfsService.java

protected void saveServiceMessage_EncryptedFile(String sHead, String sBody, byte[] aByte, String sID_Order,
        String sMail, String sFileName, String sFileContentType) {

    final Map<String, String> mParam = new HashMap<>();
    mParam.put("sHead", sHead);//" ?"
    mParam.put("sBody", sBody);
    mParam.put("sID_Order", sID_Order);
    mParam.put("sMail", sMail);
    mParam.put("sFileName", sFileName);
    mParam.put("sFileContentType", sFileContentType);
    mParam.put("nID_SubjectMessageType", "" + 12L);
    mParam.put("sID_DataLinkSource", "Region");
    mParam.put("sID_DataLinkAuthor", "SFS");
    String sID_DataLink;//from w w  w  . j  av  a  2  s .c o m
    sID_DataLink = durableBytesDataStorage.saveData(aByte); //sBody.getBytes(Charset.forName("UTF-8"))
    mParam.put("sID_DataLink", sID_DataLink);

    mParam.put("RequestMethod", RequestMethod.GET.name());

    LOG.info("ToJournal-PROCESS mParam=" + mParam);

    ScheduledExecutorService oScheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
    Runnable oRunnable = new Runnable() {

        @Override
        public void run() {
            LOG.info("try to save service message with params with a delay: (params={})", mParam);
            String jsonServiceMessage;
            try {
                jsonServiceMessage = historyEventService.addServiceMessage(mParam);
                LOG.info("(jsonServiceMessage={})", jsonServiceMessage);
            } catch (Exception e) {
                LOG.error("( saveServiceMessage error={})", e.getMessage());
            }
        }
    };
    // run saving message in 10 seconds so history event will be in the
    // database already by that time
    oScheduledExecutorService.schedule(oRunnable, 10, TimeUnit.SECONDS);
    oScheduledExecutorService.shutdown();

    LOG.info("Configured thread to run in 10 seconds with params: (params={})", mParam);
}