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:Main.java

public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(600, 400);//from  w w w  .ja va2  s. c  om
    frame.setVisible(true);
    Executors.newScheduledThreadPool(1).scheduleAtFixedRate(() -> {
        System.out.println(frame.getLocation());
    }, 0, 1000, TimeUnit.MILLISECONDS);
}

From source file:Main.java

public static void main(String args[]) {
    executor = Executors.newScheduledThreadPool(1);
    runnable = new Runnable() {
        @Override/*from ww w.j  a  v a 2  s.  c om*/
        public void run() {
            System.out.println("Inside runnable" + i++);
        }
    };
    future = executor.scheduleWithFixedDelay(runnable, 0, 2, TimeUnit.SECONDS);
    try {
        Thread.sleep(4000); // sleeping for 2 seconds
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    future.cancel(false);
    future = executor.scheduleWithFixedDelay(runnable, 0, 10, TimeUnit.SECONDS);
}

From source file:ScheduledTask.java

public static void main(String[] args) {
    // Get an executor with 3 threads
    ScheduledExecutorService sexec = Executors.newScheduledThreadPool(3);

    ScheduledTask task1 = new ScheduledTask(1);
    ScheduledTask task2 = new ScheduledTask(2);

    // Task #1 will run after 2 seconds
    sexec.schedule(task1, 2, TimeUnit.SECONDS);

    // Task #2 runs after 5 seconds delay and keep running every 10 seconds
    sexec.scheduleAtFixedRate(task2, 5, 10, TimeUnit.SECONDS);

    try {//from  w  w  w. j  a  v a 2 s. c om
        TimeUnit.SECONDS.sleep(60);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    sexec.shutdown();
}

From source file:io.smartspaces.service.comm.network.server.internal.netty.NettyUdpBroadcastMasterNetworkCommunicationEndpoint.java

public static void main(String[] args) throws Exception {
    ExecutorService executorService = Executors.newScheduledThreadPool(1000);
    NettyUdpBroadcastMasterNetworkCommunicationEndpoint endpoint = new NettyUdpBroadcastMasterNetworkCommunicationEndpoint(
            23867, executorService, new StandardExtendedLog("foo", new Jdk14Logger("foo")));
    endpoint.startup();//from  ww w .  ja va 2  s  .  c om

    Thread.sleep(1000);
    for (int i = 0; i < 10; i++) {
        endpoint.writeBroadcastData("Hello".getBytes());
        Thread.sleep(1000);
    }

    endpoint.shutdown();
    executorService.shutdown();
}

From source file:interactivespaces.hardware.driver.gaming.wilddivine.IomDriver.java

public static void main(String[] args) {
    final SimpleInteractiveSpacesEnvironment spaceEnvironment = new SimpleInteractiveSpacesEnvironment();
    spaceEnvironment.setExecutorService(Executors.newScheduledThreadPool(100));
    SimpleServiceRegistry serviceRegistry = new SimpleServiceRegistry(spaceEnvironment);
    spaceEnvironment.setServiceRegistry(serviceRegistry);
    Configuration configuration = SimpleConfiguration.newConfiguration();
    spaceEnvironment.setLog(new Jdk14Logger("foo"));
    Usb4JavaUsbCommunicationEndpointService service = new Usb4JavaUsbCommunicationEndpointService();
    serviceRegistry.registerService(service);
    service.startup();/*from   w w  w  .j a va2 s  . c o  m*/

    IomDriver driver = new IomDriver();
    driver.prepare(spaceEnvironment, configuration, spaceEnvironment.getLog());

    driver.addListener(new IomDeviceListener() {

        @Override
        public void onEvent(IomDriver driver, double heartRateValue, double skinConductivityLevel) {
            spaceEnvironment.getLog()
                    .info(String.format("Heart is %f, skin is %f", heartRateValue, skinConductivityLevel));
        }
    });

    try {
        driver.startup();

        InteractiveSpacesUtilities.delay(20000);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        driver.shutdown();
        spaceEnvironment.getExecutorService().shutdown();
    }
}

From source file:org.sourcepit.consul.forwarder.Main.java

public static void main(String[] args) {

    final String dockerUri = "http://192.168.56.101:2375";
    final String consulUri = "http://192.168.56.101:8500";

    final int fetchConsulStateInterval = 30;
    final int fetchDockerStateInterval = 30;
    final int dispatchItemsInterval = 2;
    final int requestDockerStateDelay = 5;

    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
    connManager.setDefaultMaxPerRoute(10);
    final HttpClient httpClient = HttpClients.createMinimal(connManager);

    final BlockingQueue<JsonObject> queue = new LinkedBlockingQueue<>();

    final FetchConsulStateCmd fetchConsulStateCmd = new FetchConsulStateCmd(httpClient, consulUri) {
        @Override//from  w w w  . j av a 2  s.c o  m
        protected void doHandle(JsonObject consulState) {
            final JsonObject item = createItem("ConsulState", consulState);
            LOG.debug(item.toString());
            queue.add(item);
        }

    };

    final FetchDockerStateCmd fetchDockerStateCmd = new FetchDockerStateCmd(httpClient, dockerUri) {
        @Override
        protected void doHandle(JsonArray dockerState) {
            final JsonObject item = createItem("DockerState", dockerState);
            LOG.debug(item.toString());
            queue.add(item);
        }
    };

    final ConsulForwarderState forwarderState = new ConsulForwarderState();

    final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    scheduler.scheduleAtFixedRate(fetchConsulStateCmd, 0, fetchConsulStateInterval, TimeUnit.SECONDS);
    scheduler.scheduleAtFixedRate(fetchDockerStateCmd, 0, fetchDockerStateInterval, TimeUnit.SECONDS);
    scheduler.scheduleAtFixedRate(new DispatchItemsCmd(queue) {
        @Override
        protected void handleDockerState(JsonArray dockerState) {
            forwarderState.applyDockerState(dockerState);
        }

        @Override
        protected void handleDockerEvents(JsonArray dockerEvents) {
            // trigger docker state update
            scheduler.schedule(fetchDockerStateCmd, requestDockerStateDelay, TimeUnit.SECONDS);
        }

        @Override
        protected void handleConsulState(JsonObject consulState) {
            forwarderState.applyConsulState(consulState);
        }
    }, 0, dispatchItemsInterval, TimeUnit.SECONDS);

    final DockerEventObserver eventObserver = new DockerEventObserver(httpClient, dockerUri) {
        @Override
        protected void handle(JsonObject event) {
            queue.add(createItem("DockerEvent", event));
        }
    };

    final Thread eventObserverThread = new Thread(eventObserver, "Docker Event Observer") {
        @Override
        public void interrupt() {
            eventObserver.die();
            super.interrupt();
        }
    };
    eventObserverThread.start();
}

From source file:de.meldanor.autothesis.Core.java

public static void main(String[] args) {
    try {/*from   ww  w.  java 2 s  .c  o  m*/
        AutoThesisCommandOption options = AutoThesisCommandOption.getInstance();
        CommandLine commandLine = new GnuParser().parse(options, args);

        // Missing commands
        if (!commandLine.hasOption(options.getUserCommand())
                || !commandLine.hasOption(options.getTokenCommand())
                || !commandLine.hasOption(options.getRepoCommand())) {
            new HelpFormatter().printHelp("autothesis", options);
            return;
        }

        String user = commandLine.getOptionValue(options.getUserCommand());
        String repo = commandLine.getOptionValue(options.getRepoCommand());
        String token = commandLine.getOptionValue(options.getTokenCommand());

        logger.info("Hello World, this is AutoThesis!");
        long intervalMinutes = Long.parseLong(commandLine.getOptionValue(options.getIntervalCommand(), "60"));
        logger.info("Check for update interval: " + intervalMinutes + " min");
        final AutoThesis autoThesis = new AutoThesis(user, repo, token);
        Executors.newScheduledThreadPool(1).scheduleAtFixedRate(() -> {
            try {
                autoThesis.execute();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }, 0, intervalMinutes, TimeUnit.MINUTES);

    } catch (Exception e) {
        logger.throwing(Level.ERROR, e);
    }
}

From source file:eu.itesla_project.online.mpi.Master.java

public static void main(String[] args) throws Exception {
    try {//from   www  . j a v  a2s . c o m
        CommandLineParser parser = new GnuParser();
        CommandLine line = parser.parse(OPTIONS, args);

        String mode = line.getOptionValue("m");
        Path tmpDir = Paths.get(line.getOptionValue("t"));
        Class<?> statisticsFactoryClass = Class.forName(line.getOptionValue("f"));
        Path statisticsDbDir = Paths.get(line.getOptionValue("s"));
        String statisticsDbName = line.getOptionValue("d");
        int coresPerRank = Integer.parseInt(line.getOptionValue("n"));
        Path stdOutArchive = line.hasOption("o") ? Paths.get(line.getOptionValue("o")) : null;

        MpiExecutorContext mpiExecutorContext = new MultiStateNetworkAwareMpiExecutorContext();
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
        ExecutorService executorService = MultiStateNetworkAwareExecutors.newCachedThreadPool();
        try {
            MpiStatisticsFactory statisticsFactory = statisticsFactoryClass
                    .asSubclass(MpiStatisticsFactory.class).newInstance();
            MpiStatistics statistics = statisticsFactory.create(statisticsDbDir, statisticsDbName);
            try (ComputationManager computationManager = new MpiComputationManager(tmpDir, statistics,
                    mpiExecutorContext, coresPerRank, false, stdOutArchive)) {
                OnlineConfig config = OnlineConfig.load();
                try (LocalOnlineApplication application = new LocalOnlineApplication(config, computationManager,
                        scheduledExecutorService, executorService, true)) {
                    switch (mode) {
                    case "ui":
                        System.out.println("LocalOnlineApplication created");
                        System.out.println("Waiting till shutdown");
                        // indefinitely wait for JMX commands
                        //TimeUnit.DAYS.sleep(Integer.MAX_VALUE);
                        synchronized (application) {
                            try {
                                application.wait();
                            } catch (InterruptedException ex) {
                            }

                        }
                        break;
                    default:
                        throw new IllegalArgumentException("Invalid mode " + mode);
                    }
                }
            }
        } finally {
            mpiExecutorContext.shutdown();
            executorService.shutdown();
            scheduledExecutorService.shutdown();
            executorService.awaitTermination(15, TimeUnit.MINUTES);
            scheduledExecutorService.awaitTermination(15, TimeUnit.MINUTES);
        }
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("master", OPTIONS, true);
        System.exit(-1);
    } catch (Throwable t) {
        LOGGER.error(t.toString(), t);
        System.exit(-1);
    }
}

From source file:com.pushtechnology.consulting.Benchmarker.java

public static void main(String[] args) throws InterruptedException {
    LOG.info("Starting Java Benchmark Suite v{}", Benchmarker.class.getPackage().getImplementationVersion());

    final Arguments arguments = Arguments.parse(args);

    try {// w ww.j a  v  a 2  s  . c  o m
        LOG.debug("Trying to set client InboundThreadPool queue size to '{}'", CLIENT_INBOUND_QUEUE_QUEUE_SIZE);
        final ThreadsConfig threadsConfig = ConfigManager.getConfig().getThreads();
        final ThreadPoolConfig inboundPool = threadsConfig.addPool(CLIENT_INBOUND_THREAD_POOL_NAME);
        inboundPool.setQueueSize(CLIENT_INBOUND_QUEUE_QUEUE_SIZE);
        inboundPool.setCoreSize(CLIENT_INBOUND_QUEUE_CORE_SIZE);
        inboundPool.setMaximumSize(CLIENT_INBOUND_QUEUE_MAX_SIZE);
        threadsConfig.setInboundPool(CLIENT_INBOUND_THREAD_POOL_NAME);
        LOG.debug("Successfully set client InboundThreadPool queue size to '{}'",
                CLIENT_INBOUND_QUEUE_QUEUE_SIZE);
    } catch (APIException ex) {
        LOG.error("Failed to set client inbound pool size to '{}'", CLIENT_INBOUND_QUEUE_QUEUE_SIZE);
        ex.printStackTrace();
    }

    connectThreadPool = Executors.newScheduledThreadPool(arguments.connectThreadPoolSize);
    final Publisher publisher;

    if (arguments.doPublish) {
        LOG.info("Creating Publisher with connection string: '{}'", arguments.publisherConnectionString);
        publisher = new Publisher(arguments.publisherConnectionString, arguments.publisherUsername,
                arguments.publisherPassword, arguments.topics, arguments.topicType);
        publisher.start();

        publisherMonitor = globalThreadPool.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                LOG.trace("publisherMonitor fired");
                LOG.info("There are {} publishers running for topics: '{}'",
                        publisher.getUpdaterFuturessByTopic().size(),
                        ArrayUtils.toString(publisher.getUpdaterFuturessByTopic().keySet()));
                for (ScheduledFuture<?> svc : publisher.getUpdaterFuturessByTopic().values()) {
                    if (svc.isCancelled()) {
                        LOG.debug("Service is cancelled...");
                    }
                    if (svc.isDone()) {
                        LOG.debug("Service is done...");
                    }
                }
                LOG.trace("Done publisherMonitor fired");
            }
        }, 2L, 5L, SECONDS);
    } else {
        publisher = null;
    }

    /* Create subscribing sessions. Finite or churning */
    if (arguments.doCreateSessions) {
        if (arguments.maxNumSessions > 0) {
            LOG.info("Creating {} Sessions with connection string: '{}'", arguments.maxNumSessions,
                    arguments.sessionConnectionString);
        } else {
            LOG.info("Creating Sessions with connection string: '{}s'", arguments.sessionConnectionString);
            LOG.info("Creating Sessions at {}/second, disconnecting after {} seconds", arguments.sessionRate,
                    arguments.sessionDuration);
        }
        sessionCreator = new SessionCreator(arguments.sessionConnectionString, arguments.myTopics,
                arguments.topicType);

        LOG.info(
                "Sessions: [Connected] [Started] [Recovering] [Closed] [Ended] [Failed]  | Messages: [Number] [Bytes]");
        sessionsCounter = globalThreadPool.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                LOG.trace("sessionsCounter fired");
                LOG.info("Sessions: {} {} {} {} {} {} | Messages: {} {}",
                        sessionCreator.getConnectedSessions().get(), sessionCreator.getStartedSessions().get(),
                        sessionCreator.getRecoveringSessions().get(), sessionCreator.getClosedSessions().get(),
                        sessionCreator.getEndedSessions().get(), sessionCreator.getConnectionFailures().get(),
                        sessionCreator.getMessageCount().getAndSet(0),
                        sessionCreator.getMessageByteCount().getAndSet(0));
                LOG.trace("Done sessionsCounter fired");
            }
        }, 0L, 5L, SECONDS);

        if (arguments.maxNumSessions > 0) {
            sessionCreator.start(arguments.maxNumSessions);
        } else {
            sessionCreator.start(arguments.sessionRate, arguments.sessionDuration);
        }
    }

    RUNNING_LATCH.await();

    if (arguments.doPublish) {
        if (publisher != null) {
            publisher.shutdown();
        }
        publisherMonitor.cancel(false);
    }

    if (arguments.doCreateSessions) {
        sessionCreator.shutdown();
        sessionsCounter.cancel(false);
    }

    if (!globalThreadPool.isTerminated()) {
        try {
            globalThreadPool.awaitTermination(1L, SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.mapr.synth.Synth.java

public static void main(String[] args)
        throws IOException, CmdLineException, InterruptedException, ExecutionException {
    final Options opts = new Options();
    CmdLineParser parser = new CmdLineParser(opts);
    try {/*from   ww w.  ja va2 s .c  o  m*/
        parser.parseArgument(args);
    } catch (CmdLineException e) {
        System.err.println("Usage: " + "[ -count <number>G|M|K ] " + "-schema schema-file "
                + "[-quote DOUBLE_QUOTE|BACK_SLASH|OPTIMISTIC] " + "[-format JSON|TSV|CSV|XML ] "
                + "[-threads n] " + "[-output output-directory-name] ");
        throw e;
    }
    Preconditions.checkArgument(opts.threads > 0 && opts.threads <= 2000,
            "Must have at least one thread and no more than 2000");

    if (opts.threads > 1) {
        Preconditions.checkArgument(!"-".equals(opts.output),
                "If more than on thread is used, you have to use -output to set the output directory");
    }

    File outputDir = new File(opts.output);
    if (!"-".equals(opts.output)) {
        if (!outputDir.exists()) {
            Preconditions.checkState(outputDir.mkdirs(),
                    String.format("Couldn't create output directory %s", opts.output));
        }
        Preconditions.checkArgument(outputDir.exists() && outputDir.isDirectory(),
                String.format("Couldn't create directory %s", opts.output));
    }

    if (opts.schema == null) {
        throw new IllegalArgumentException("Must specify schema file using [-schema filename] option");
    }
    final SchemaSampler sampler = new SchemaSampler(opts.schema);
    final AtomicLong rowCount = new AtomicLong();

    final List<ReportingWorker> tasks = Lists.newArrayList();
    int limit = (opts.count + opts.threads - 1) / opts.threads;
    int remaining = opts.count;
    for (int i = 0; i < opts.threads; i++) {

        final int count = Math.min(limit, remaining);
        remaining -= count;

        tasks.add(new ReportingWorker(opts, sampler, rowCount, count, i));
    }

    final double t0 = System.nanoTime() * 1e-9;
    ExecutorService pool = Executors.newFixedThreadPool(opts.threads);
    ScheduledExecutorService blinker = Executors.newScheduledThreadPool(1);
    final AtomicBoolean finalRun = new AtomicBoolean(false);

    final PrintStream sideLog = new PrintStream(new FileOutputStream("side-log"));
    Runnable blink = new Runnable() {
        public double oldT;
        private long oldN;

        @Override
        public void run() {
            double t = System.nanoTime() * 1e-9;
            long n = rowCount.get();
            System.err.printf("%s\t%d\t%.1f\t%d\t%.1f\t%.3f\n", finalRun.get() ? "F" : "R", opts.threads,
                    t - t0, n, n / (t - t0), (n - oldN) / (t - oldT));
            for (ReportingWorker task : tasks) {
                ReportingWorker.ThreadReport r = task.report();
                sideLog.printf("\t%d\t%.2f\t%.2f\t%.2f\t%.1f\t%.1f\n", r.fileNumber, r.threadTime, r.userTime,
                        r.wallTime, r.rows / r.threadTime, r.rows / r.wallTime);
            }
            oldN = n;
            oldT = t;
        }
    };
    if (!"-".equals(opts.output)) {
        blinker.scheduleAtFixedRate(blink, 0, 10, TimeUnit.SECONDS);
    }
    List<Future<Integer>> results = pool.invokeAll(tasks);

    int total = 0;
    for (Future<Integer> result : results) {
        total += result.get();
    }
    Preconditions.checkState(total == opts.count, String
            .format("Expected to generate %d lines of output, but actually generated %d", opts.count, total));
    pool.shutdownNow();
    blinker.shutdownNow();
    finalRun.set(true);
    sideLog.close();
    blink.run();
}