Example usage for java.util.concurrent ScheduledExecutorService scheduleAtFixedRate

List of usage examples for java.util.concurrent ScheduledExecutorService scheduleAtFixedRate

Introduction

In this page you can find the example usage for java.util.concurrent ScheduledExecutorService scheduleAtFixedRate.

Prototype

public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit);

Source Link

Document

Submits a periodic action that becomes enabled first after the given initial delay, and subsequently with the given period; that is, executions will commence after initialDelay , then initialDelay + period , then initialDelay + 2 * period , and so on.

Usage

From source file:com.omade.monitor.ClientApplication.java

public static void executeFixedRate() {
    ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
    executor.scheduleAtFixedRate(
            new DoTask(config.getProperty("server.url"), config.getProperty("server.port")), 0, 1,
            TimeUnit.SECONDS);/*  w w w  . java2s . c  o m*/
}

From source file:com.omade.monitor.ClientApplication.java

public static void newVersionCheck() {
    ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
    executor.scheduleAtFixedRate(
            new DoTask(config.getProperty("server.url"), config.getProperty("server.port")), 0, 1,
            TimeUnit.SECONDS);/*  www.  j  av  a2 s  .  c o m*/
}

From source file:com.garethahealy.jolokiajvmhawkular.core.EmbeddedHawkularMetricsAgent.java

public static void premain(String agentArgs) {
    CustomJvmAgent.premain(agentArgs);/*w w w  .  j ava 2s. c om*/

    try {
        LOG.info("About to load BackendManager...");

        Field jolokiaHttpHandlerField = FieldUtils.getDeclaredField(server.getClass(), "jolokiaHttpHandler",
                true);
        JolokiaHttpHandler jolokiaHttpHandler = (JolokiaHttpHandler) jolokiaHttpHandlerField.get(server);

        Field backendManagerField = FieldUtils.getDeclaredField(jolokiaHttpHandler.getClass(), "backendManager",
                true);
        BackendManager backendManager = (BackendManager) backendManagerField.get(jolokiaHttpHandler);

        HawkularClient client = getHawkularClient();
        if (client == null) {
            LOG.error(
                    "HawkularClient is null. Not starting HawkularMetricsService via ScheduledExecutorService.");
        } else {
            BasicThreadFactory factory = new BasicThreadFactory.Builder().namingPattern("hawkular-metrics-%d")
                    .daemon(true).priority(Thread.MAX_PRIORITY).build();

            ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor(factory);
            exec.scheduleAtFixedRate(
                    new HawkularMetricsRunnable(new HawkularMetricsService(backendManager, client)), 15, 15,
                    TimeUnit.SECONDS);

            LOG.info("Started HawkularMetricsService via ScheduledExecutorService.");
        }
    } catch (IllegalAccessException e) {
        LOG.error("{}", e);
    }
}

From source file:com.acmutv.ontoqa.tool.runtime.RuntimeManager.java

/**
 * Registers a periodic task./*w w  w  . j  a  v a 2 s.  c  o m*/
 * @param task the task to execute.
 * @param delay the delay to first execution.
 * @param period the period between executions.
 * @param timeout the time to interruption.
 * @param unit the time unit.
 */
private static void registerPeriodic(Runnable task, long delay, long period, long timeout, TimeUnit unit) {
    final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    final ScheduledFuture<?> handler = scheduler.scheduleAtFixedRate(task, delay, period, unit);

    if (timeout > 0) {
        Runnable interrupt = () -> handler.cancel(true);
        scheduler.schedule(interrupt, timeout, TimeUnit.SECONDS);
    }
}

From source file:org.graylog2.Main.java

private static void initializeHostCounterCache(ScheduledExecutorService scheduler) {

    scheduler.scheduleAtFixedRate(new HostCounterCacheWriterThread(),
            HostCounterCacheWriterThread.INITIAL_DELAY, HostCounterCacheWriterThread.PERIOD, TimeUnit.SECONDS);

    LOG.info("Host count cache is up.");
}

From source file:org.graylog2.Main.java

private static void initializeMessageCounters(ScheduledExecutorService scheduler) {

    scheduler.scheduleAtFixedRate(new MessageCountWriterThread(), MessageCountWriterThread.INITIAL_DELAY,
            MessageCountWriterThread.PERIOD, TimeUnit.SECONDS);

    LOG.info("Message counters initialized.");
}

From source file:org.graylog2.Main.java

private static void initializeServerValueWriter(ScheduledExecutorService scheduler) {

    scheduler.scheduleAtFixedRate(new ServerValueWriterThread(), ServerValueWriterThread.INITIAL_DELAY,
            ServerValueWriterThread.PERIOD, TimeUnit.SECONDS);

    LOG.info("Server value writer up.");
}

From source file:com.twitter.hraven.hadoopJobMonitor.metrics.HadoopJobMonitorMetrics.java

static HadoopJobMonitorMetrics create(Configuration conf) {
    MetricsSystem ms = DefaultMetricsSystem.instance();

    HadoopJobMonitorMetrics metricObject = new HadoopJobMonitorMetrics();
    MetricsSourceBuilder sb = MetricsAnnotations.newSourceBuilder(metricObject);
    final MetricsSource s = sb.build();
    ms.register("HadoopJobMonitorMetrics", "The Metrics of HadoopJobMonitor service", s);

    ScheduledExecutorService heartbeatExecutor = Executors
            .newSingleThreadScheduledExecutor(new SimpleThreadFactory());
    heartbeatExecutor.scheduleAtFixedRate(metricObject.new Heart(), 0, 1, TimeUnit.MINUTES);
    return metricObject;
}

From source file:org.graylog2.Main.java

private static void initializeGELFThreads(String gelfAddress, int gelfPort,
        ScheduledExecutorService scheduler) {
    GELFMainThread gelfThread = new GELFMainThread(new InetSocketAddress(gelfAddress, gelfPort));
    gelfThread.start();//w  ww . jav  a 2s .  c o  m

    scheduler.scheduleAtFixedRate(new ChunkedGELFClientManagerThread(ChunkedGELFClientManager.getInstance()),
            ChunkedGELFClientManagerThread.INITIAL_DELAY, ChunkedGELFClientManagerThread.PERIOD,
            TimeUnit.SECONDS);

    LOG.info("GELF threads started");
}

From source file:de.dal33t.powerfolder.PowerFolder.java

/**
 * Starts a PowerFolder controller with the given command line arguments
 *
 * @param args// ww w  .jav a 2 s. com
 */
public static void startPowerFolder(String[] args) {

    // Touch Logger immediately to initialize handlers.
    LoggingManager.isLogToFile();

    // Default exception logger
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        public void uncaughtException(Thread t, Throwable e) {
            e.printStackTrace();
            log.log(Level.SEVERE, "Exception in " + t + ": " + e.toString(), e);
        }
    });

    CommandLine commandLine = parseCommandLine(args);
    if (commandLine == null) {
        return;
    }

    // -l --log console log levels (severe, warning, info, fine and finer).
    if (commandLine.hasOption("l")) {
        String levelName = commandLine.getOptionValue("l");
        Level level = LoggingManager.levelForName(levelName);
        if (level != null) {
            LoggingManager.setConsoleLogging(level);
        }
    }

    if (commandLine.hasOption("s")) {
        // Server mode, suppress debug output on console
        // Logger.addExcludeConsoleLogLevel(Logger.DEBUG);
    }

    if (commandLine.hasOption("h")) {
        // Show help
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("PowerFolder", COMMAND_LINE_OPTIONS);
        return;
    }

    int rconPort = Integer.valueOf(ConfigurationEntry.NET_RCON_PORT.getDefaultValue());
    String portStr = commandLine.getOptionValue("k");
    if (StringUtils.isNotBlank(portStr)) {
        try {
            rconPort = Integer.valueOf(portStr.trim());
        } catch (Exception e) {
            log.warning("Unable to parse rcon port: " + portStr + ". " + e);
        }
    }

    boolean runningInstanceFound = RemoteCommandManager.hasRunningInstance(rconPort);

    if (commandLine.hasOption("k")) {
        if (runningInstanceFound) {
            System.out.println("Stopping " + NAME);
            // Send quit command
            RemoteCommandManager.sendCommand(rconPort, RemoteCommandManager.QUIT);
        } else {
            System.err.println("Process not running");
        }

        // stop
        return;
    }

    // set language from commandline to preferences
    if (commandLine.hasOption("g")) {
        Preferences.userNodeForPackage(Translation.class).put("locale", commandLine.getOptionValue("g"));
    }

    if (JavaVersion.systemVersion().isOpenJDK()) {
        Object[] options = { "Open Oracle home page and exit", "Exit" };

        int n = JOptionPane.showOptionDialog(null,
                "You are using OpenJDK which is unsupported.\n"
                        + "Please install the client with bundled JRE or install the Oracle JRE",
                "Unsupported JRE", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null, options,
                options[0]);

        if (n == 0) {
            try {
                BrowserLauncher.openURL("http://www.java.com");
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }

        return;
    }

    // The controller.
    Controller controller = Controller.createController();

    String[] files = commandLine.getArgs();
    // Parsing of command line completed

    boolean commandContainsRemoteCommands = files != null && files.length >= 1 || commandLine.hasOption("e")
            || commandLine.hasOption("r") || commandLine.hasOption("a");
    // Try to start controller
    boolean startController = !commandContainsRemoteCommands || !runningInstanceFound;
    try {
        log.info("PowerFolder v" + Controller.PROGRAM_VERSION);

        // Start controller
        if (startController) {
            controller.startConfig(commandLine);
        }

        // Send remote command if there a files in commandline
        if (files != null && files.length > 0) {
            // Parse filenames and build remote command
            StringBuilder openFilesRCommand = new StringBuilder(RemoteCommandManager.OPEN);

            for (String file : files) {
                openFilesRCommand.append(file);
                // FIXME: Add ; separator ?
            }

            // Send remote command to running PowerFolder instance
            RemoteCommandManager.sendCommand(openFilesRCommand.toString());
        }

        if (commandLine.hasOption("e")) {
            RemoteCommandManager.sendCommand(RemoteCommandManager.MAKEFOLDER + commandLine.getOptionValue("e"));
        }
        if (commandLine.hasOption("r")) {
            RemoteCommandManager
                    .sendCommand(RemoteCommandManager.REMOVEFOLDER + commandLine.getOptionValue("r"));
        }
        if (commandLine.hasOption("a")) {
            RemoteCommandManager.sendCommand(RemoteCommandManager.COPYLINK + commandLine.getOptionValue("a"));
        }
    } catch (Throwable t) {
        t.printStackTrace();
        log.log(Level.SEVERE, "Throwable", t);
        return;
    }

    // Begin monitoring memory usage.
    if (controller.isStarted() && controller.isUIEnabled()) {
        ScheduledExecutorService service = controller.getThreadPool();
        service.scheduleAtFixedRate(new MemoryMonitor(controller), 1, 1, TimeUnit.MINUTES);
    }

    // Not go into console mode if ui is open
    if (!startController) {
        if (runningInstanceFound) {
            RemoteCommandManager.sendCommand(RemoteCommandManager.SHOW_UI);
        }
        return;
    }

    System.out.println("------------ " + NAME + " " + Controller.PROGRAM_VERSION + " started ------------");

    boolean restartRequested = false;
    do {
        // Go into restart loop
        while (controller.isStarted() || controller.isShuttingDown()) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                log.log(Level.WARNING, "InterruptedException", e);
                return;
            }
        }

        restartRequested = controller.isRestartRequested();
        if (restartRequested) {
            Map<Thread, StackTraceElement[]> threads = Thread.getAllStackTraces();
            for (Thread thread : threads.keySet()) {
                if (thread.getName().startsWith("PoolThread") || thread.getName().startsWith("Reconnector")
                        || thread.getName().startsWith("ConHandler")) {
                    thread.interrupt();
                }
            }
            log.info("Restarting controller");
            System.out.println(
                    "------------ " + NAME + " " + Controller.PROGRAM_VERSION + " restarting ------------");
            controller = null;
            System.gc();
            controller = Controller.createController();
            // Start controller
            controller.startConfig(commandLine);
        }
    } while (restartRequested);
}