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: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);
            }/*  w  w w. j  ava  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);
}

From source file:tv.phantombot.PhantomBot.java

/**
 * Backup the database, keeping so many days.
 *//*from ww  w.j ava 2  s  .  c  o 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.  ja  v a 2 s.  c  o  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: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));
    }//from  w ww .  ja va2s  . c om

    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);
            }// www  . j  a va2s  .com

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

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

/**
 * Backup the database, keeping so many days.
 *//*from  www  .  ja  va2 s. c o  m*/
private void doBackupSQLiteDB() {

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

    ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
    service.scheduleAtFixedRate(() -> {
        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() - (86400000 * backupSQLiteKeepDays))) {
                    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:com.netflix.conductor.tests.integration.WorkflowServiceTest.java

public void testRateLimiting() throws Exception {

    TaskDef td = new TaskDef();
    td.setName("eventX1");
    td.setTimeoutSeconds(1);/*from ww w. j ava 2s. c o m*/
    td.setConcurrentExecLimit(1);

    ms.registerTaskDef(Arrays.asList(td));

    WorkflowDef def = new WorkflowDef();
    def.setName("test_rate_limit");
    def.setSchemaVersion(2);

    WorkflowTask event = new WorkflowTask();
    event.setType("USER_TASK");
    event.setName("eventX1");
    event.setTaskReferenceName("event0");
    event.setSink("conductor");

    def.getTasks().add(event);
    ms.registerWorkflowDef(def);

    Executors.newSingleThreadScheduledExecutor().scheduleWithFixedDelay(() -> {
        queue.processUnacks("USER_TASK");
    }, 2, 2, TimeUnit.SECONDS);

    String[] ids = new String[100];
    ExecutorService es = Executors.newFixedThreadPool(10);
    for (int i = 0; i < 10; i++) {
        final int index = i;
        es.submit(() -> {
            try {
                String id = provider.startWorkflow(def.getName(), def.getVersion(), "", new HashMap<>());
                ids[index] = id;
            } catch (Exception e) {
                e.printStackTrace();
            }

        });
    }
    Uninterruptibles.sleepUninterruptibly(20, TimeUnit.SECONDS);
    for (int i = 0; i < 10; i++) {
        String id = ids[i];
        Workflow workflow = provider.getWorkflow(id, true);
        assertNotNull(workflow);
        assertEquals(1, workflow.getTasks().size());

        Task eventTask = workflow.getTasks().get(0);
        assertEquals(Task.Status.COMPLETED, eventTask.getStatus());
        assertEquals("tasks:" + workflow.getTasks(), WorkflowStatus.COMPLETED, workflow.getStatus());
        assertTrue(!eventTask.getOutputData().isEmpty());
        assertNotNull(eventTask.getOutputData().get("event_produced"));
    }
}