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.oneops.metrics.OneOpsMetrics.java

private void addIbatisMetrics() {
    ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
    int initialDelay = 10;
    //scheduled with ibatis
    //getMap and register all meters with id and avg time .
    Runnable registerMetrics = () -> {
        Map<String, Stats> metrics = StatsPlugin.getStatsMap();
        try {// w ww .j  av  a  2  s .  c  o  m
            final SortedSet<String> registeredMetrics = ooMetricsRegistry.getNames();
            final long count = metrics.entrySet().parallelStream().map((e) -> {
                Meter m = ooMetricsRegistry.meter(e.getKey());
                if (m.getCount() != e.getValue().getNoOfCalls()) {
                    ooMetricsRegistry.meter(e.getKey()).mark(e.getValue().getNoOfCalls() - m.getCount());
                }
                if (!registeredMetrics.contains(e.getKey() + "_avg")) {
                    ooMetricsRegistry.register(e.getKey() + "_avg", (Gauge<Double>) e.getValue()::getAverage);
                }
                if (!registeredMetrics.contains(e.getKey() + "_max")) {
                    ooMetricsRegistry.register(e.getKey() + "_max", (Gauge<Long>) e.getValue()::getMaxTime);
                }
                return 1;
            }).count();

        } catch (Exception e) {
            logger.warn("There was an error in reporting metrics", e);
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Finished reporting metrics for ibatis" + metrics.size());
        }
    };

    executor.scheduleAtFixedRate(registerMetrics, initialDelay, 60, TimeUnit.SECONDS);
}

From source file:org.wso2.carbon.repository.core.handlers.builtin.OperationStatisticsHandler.java

private static synchronized void initializeStatisticsLogging() {
    if (executor != null) {
        return;//from w w w .ja  va 2s.  co m
    }
    records = new HashMap<Method, Long>();
    executor = Executors.newCachedThreadPool();
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            executor.shutdownNow();
        }
    });

    for (Method method : new Method[] { Method.GET, Method.PUT, Method.IMPORT, Method.MOVE, Method.COPY,
            Method.RENAME, Method.DELETE, Method.ADD_ASSOCIATION, Method.REMOVE_ASSOCIATION,
            Method.GET_ASSOCIATIONS, Method.GET_ALL_ASSOCIATIONS, Method.EXECUTE_QUERY, Method.RESOURCE_EXISTS,
            Method.DUMP, Method.RESTORE }) {
        records.put(method, 0l);
    }

    final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();

    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            scheduler.shutdownNow();
        }
    });

    Runnable runnable = new Runnable() {
        public void run() {
            if (records == null) {
                log.error("Unable to store operation statistics.");
            } else {
                synchronized (this) {
                    statsLog.debug("Total Number of get calls                : " + records.get(Method.GET));
                    statsLog.debug("Total Number of put calls                : " + records.get(Method.PUT));
                    statsLog.debug("Total Number of import calls             : " + records.get(Method.IMPORT));
                    statsLog.debug("Total Number of move calls               : " + records.get(Method.MOVE));
                    statsLog.debug("Total Number of copy calls               : " + records.get(Method.COPY));
                    statsLog.debug("Total Number of rename calls             : " + records.get(Method.RENAME));
                    statsLog.debug("Total Number of delete calls             : " + records.get(Method.DELETE));
                    statsLog.debug("Total Number of addAssociation calls     : "
                            + records.get(Method.ADD_ASSOCIATION));
                    statsLog.debug("Total Number of removeAssociation calls  : "
                            + records.get(Method.REMOVE_ASSOCIATION));
                    statsLog.debug("Total Number of getAssociations calls    : "
                            + records.get(Method.GET_ASSOCIATIONS));
                    statsLog.debug("Total Number of getAllAssociations calls : "
                            + records.get(Method.GET_ALL_ASSOCIATIONS));
                    statsLog.debug(
                            "Total Number of executeQuery calls       : " + records.get(Method.EXECUTE_QUERY));
                    statsLog.debug("Total Number of resourceExists calls     : "
                            + records.get(Method.RESOURCE_EXISTS));
                    statsLog.debug("Total Number of dump calls               : " + records.get(Method.DUMP));
                    statsLog.debug("Total Number of restore calls            : " + records.get(Method.RESTORE));
                }
            }
        }
    };

    scheduler.scheduleAtFixedRate(runnable, 60, 60, TimeUnit.SECONDS);
}

From source file:org.wso2.carbon.registry.core.jdbc.handlers.builtin.OperationStatisticsHandler.java

private static synchronized void initializeStatisticsLogging() {
    if (executor != null) {
        return;//from w w w  . j a  v  a 2s.  c  om
    }
    records = new HashMap<String, Long>();
    executor = Executors.newCachedThreadPool();
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            executor.shutdownNow();
        }
    });
    for (String s : new String[] { Filter.GET, Filter.PUT, Filter.IMPORT, Filter.MOVE, Filter.COPY,
            Filter.RENAME, Filter.DELETE, Filter.ADD_ASSOCIATION, Filter.REMOVE_ASSOCIATION,
            Filter.GET_ASSOCIATIONS, Filter.GET_ALL_ASSOCIATIONS, Filter.EXECUTE_QUERY, Filter.RESOURCE_EXISTS,
            Filter.DUMP, Filter.RESTORE }) {
        records.put(s, 0l);
    }
    final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            scheduler.shutdownNow();
        }
    });
    Runnable runnable = new Runnable() {
        public void run() {
            if (records == null) {
                log.error("Unable to store operation statistics.");
            } else {
                synchronized (this) {
                    statsLog.debug("Total Number of get calls                : " + records.get(Filter.GET));
                    statsLog.debug("Total Number of put calls                : " + records.get(Filter.PUT));
                    statsLog.debug("Total Number of import calls             : " + records.get(Filter.IMPORT));
                    statsLog.debug("Total Number of move calls               : " + records.get(Filter.MOVE));
                    statsLog.debug("Total Number of copy calls               : " + records.get(Filter.COPY));
                    statsLog.debug("Total Number of rename calls             : " + records.get(Filter.RENAME));
                    statsLog.debug("Total Number of delete calls             : " + records.get(Filter.DELETE));
                    statsLog.debug("Total Number of addAssociation calls     : "
                            + records.get(Filter.ADD_ASSOCIATION));
                    statsLog.debug("Total Number of removeAssociation calls  : "
                            + records.get(Filter.REMOVE_ASSOCIATION));
                    statsLog.debug("Total Number of getAssociations calls    : "
                            + records.get(Filter.GET_ASSOCIATIONS));
                    statsLog.debug("Total Number of getAllAssociations calls : "
                            + records.get(Filter.GET_ALL_ASSOCIATIONS));
                    statsLog.debug(
                            "Total Number of executeQuery calls       : " + records.get(Filter.EXECUTE_QUERY));
                    statsLog.debug("Total Number of resourceExists calls     : "
                            + records.get(Filter.RESOURCE_EXISTS));
                    statsLog.debug("Total Number of dump calls               : " + records.get(Filter.DUMP));
                    statsLog.debug("Total Number of restore calls            : " + records.get(Filter.RESTORE));
                }
            }
        }
    };
    scheduler.scheduleAtFixedRate(runnable, 60, 60, TimeUnit.SECONDS);
}

From source file:tv.phantombot.PhantomBot.java

public void doRefreshGameWispToken() {

    long curTime = System.currentTimeMillis() / 1000L;

    if (!dataStore.exists("settings", "gameWispRefreshTime")) {
        dataStore.set("settings", "gameWispRefreshTime", String.valueOf(curTime));
    }/*from   www  .j  a va2 s.c o m*/

    ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
    service.scheduleAtFixedRate(() -> {
        Thread.currentThread().setName("tv.phantombot.PhantomBot::doRefreshGameWispToken");

        long curTime1 = System.currentTimeMillis() / 1000L;
        String lastRunStr = dataStore.GetString("settings", "", "gameWispRefreshTime");
        long lastRun = Long.parseLong(lastRunStr);
        if ((curTime1 - lastRun) > (10 * 24 * 60 * 60)) {
            // 10 days, token expires every 35.
            dataStore.set("settings", "gameWispRefreshTime", String.valueOf(curTime1));
            updateGameWispTokens(GameWispAPIv1.instance().refreshToken());
        }
    }, 0, 1, TimeUnit.DAYS);
}

From source file:tv.phantombot.PhantomBot.java

private void doCheckPhantomBotUpdate() {
    ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
    service.scheduleAtFixedRate(() -> {
        Thread.currentThread().setName("tv.phantombot.PhantomBot::doCheckPhantomBotUpdate");

        String[] newVersionInfo = GitHubAPIv3.instance().CheckNewRelease();
        if (newVersionInfo != null) {
            try {
                Thread.sleep(6000);
                print("");
                print("New PhantomBot Release Detected: " + newVersionInfo[0]);
                print("Release Changelog: https://github.com/PhantomBot/PhantomBot/releases/"
                        + newVersionInfo[0]);
                print("Download Link: " + newVersionInfo[1]);
                print("A reminder will be provided in 24 hours!");
                print("");
            } catch (InterruptedException ex) {
                com.gmt2001.Console.err.printStackTrace(ex);
            }//from   ww w  .  j  a v a2s.  c  om

            if (webEnabled) {
                dataStore.set("settings", "newrelease_info", newVersionInfo[0] + "|" + newVersionInfo[1]);
            }
        } else {
            dataStore.del("settings", "newrelease_info");
        }
    }, 0, 24, TimeUnit.HOURS);
}

From source file:tv.phantombot.PhantomBot.java

/**
 * Backup the database, keeping so many days.
 *//*from  w ww.  java  2 s  .co  m*/
private void doBackupSQLiteDB() {

    if (!dataStoreType.equals("sqlite3store")) {
        return;
    }

    ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
    service.scheduleAtFixedRate(() -> {
        Thread.currentThread().setName("tv.phantombot.PhantomBot::doBackupSQLiteDB");

        SimpleDateFormat datefmt = new SimpleDateFormat("ddMMyyyy.hhmmss");
        datefmt.setTimeZone(TimeZone.getTimeZone(timeZone));
        String timestamp = datefmt.format(new Date());

        dataStore.backupSQLite3("phantombot.auto.backup." + timestamp + ".db");

        try {
            Iterator dirIterator = FileUtils.iterateFiles(new File("./dbbackup"),
                    new WildcardFileFilter("phantombot.auto.*"), null);
            while (dirIterator.hasNext()) {
                File backupFile = (File) dirIterator.next();
                if (FileUtils.isFileOlder(backupFile,
                        (System.currentTimeMillis() - (long) (backupSQLiteKeepDays * 864e5)))) {
                    FileUtils.deleteQuietly(backupFile);
                }
            }
        } catch (Exception ex) {
            com.gmt2001.Console.err.println("Failed to clean up database backup directory: " + ex.getMessage());
        }
    }, 0, backupSQLiteHourFrequency, TimeUnit.HOURS);
}

From source file:me.gloriouseggroll.quorrabot.Quorrabot.java

public void doRefreshGameWispToken() {

    long curTime = System.currentTimeMillis() / 1000l;

    if (!dataStoreObj.exists("settings", "gameWispRefreshTime")) {
        dataStoreObj.set("settings", "gameWispRefreshTime", String.valueOf(curTime));
    }/*from   ww w.j av  a 2 s  .co m*/

    ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
    service.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            long curTime = System.currentTimeMillis() / 1000l;
            String lastRunStr = dataStoreObj.GetString("settings", "", "gameWispRefreshTime");

            long lastRun = Long.parseLong(lastRunStr);
            if ((curTime - lastRun) > (10 * 24 * 60 * 60)) { // 10 days, token expires every 35.
                dataStoreObj.set("settings", "gameWispRefreshTime", String.valueOf(curTime));
                updateGameWispTokens(GameWispAPI.instance().refreshToken());
            }
        }
    }, 0, 1, TimeUnit.DAYS);
}

From source file:com.emc.storageos.systemservices.impl.upgrade.CoordinatorClientExt.java

/**
 * Initialization method.//  w  w w .  j  av a  2  s  .co m
 * On standby site, start a thread to monitor local coordinatorsvc status
 * On active site, start a thread to monitor db quorum of each standby site
 */
public void start() {
    if (drUtil.isStandby()) {
        _log.info("Start monitoring local coordinatorsvc status on standby site");
        ScheduledExecutorService exe = Executors.newScheduledThreadPool(1, new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r, "CoordinatorsvcMonitor");
            }
        });
        // delay for a period of time to start the monitor. For DR switchover, we stop original active, then start new active. 
        // So the original active may not see the new active immediately after reboot
        exe.scheduleAtFixedRate(coordinatorSvcMonitor, 3 * COODINATOR_MONITORING_INTERVAL,
                COODINATOR_MONITORING_INTERVAL, TimeUnit.SECONDS);
    } else {
        _log.info("Start monitoring db quorum on all standby sites");
        ScheduledExecutorService exe = Executors.newScheduledThreadPool(1, new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r, "DbsvcQuorumMonitor");
            }
        });
        exe.scheduleAtFixedRate(new DbsvcQuorumMonitor(getMyNodeId(), _coordinator, dbCommonInfo), 0,
                DB_MONITORING_INTERVAL, TimeUnit.SECONDS);
    }
}

From source file:me.mast3rplan.phantombot.PhantomBot.java

public void doRefreshGameWispToken() {

    long curTime = System.currentTimeMillis() / 1000L;

    if (!dataStore.exists("settings", "gameWispRefreshTime")) {
        dataStore.set("settings", "gameWispRefreshTime", String.valueOf(curTime));
    }//  w w  w .  jav a2s  . c o  m

    ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
    service.scheduleAtFixedRate(() -> {
        long curTime1 = System.currentTimeMillis() / 1000L;
        String lastRunStr = dataStore.GetString("settings", "", "gameWispRefreshTime");
        long lastRun = Long.parseLong(lastRunStr);
        if ((curTime1 - lastRun) > (10 * 24 * 60 * 60)) {
            // 10 days, token expires every 35.
            dataStore.set("settings", "gameWispRefreshTime", String.valueOf(curTime1));
            updateGameWispTokens(GameWispAPIv1.instance().refreshToken());
        }
    }, 0, 1, TimeUnit.DAYS);
}

From source file:me.mast3rplan.phantombot.PhantomBot.java

private void doCheckPhantomBotUpdate() {
    ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
    service.scheduleAtFixedRate(() -> {
        String[] newVersionInfo = GitHubAPIv3.instance().CheckNewRelease();
        if (newVersionInfo != null) {
            try {
                Thread.sleep(6000);
                print("");
                print("New PhantomBot Release Detected: " + newVersionInfo[0]);
                print("Release Changelog: https://github.com/PhantomBot/PhantomBot/releases/"
                        + newVersionInfo[0]);
                print("Download Link: " + newVersionInfo[1]);
                print("A reminder will be provided in 24 hours!");
                print("");
            } catch (InterruptedException ex) {
                com.gmt2001.Console.err.printStackTrace(ex);
            }//from w w  w .ja va  2 s. c o m

            if (webEnabled) {
                dataStore.set("settings", "newrelease_info", newVersionInfo[0] + "|" + newVersionInfo[1]);
            }
        } else {
            dataStore.del("settings", "newrelease_info");
        }
    }, 0, 24, TimeUnit.HOURS);
}