Example usage for java.util.concurrent ScheduledExecutorService scheduleWithFixedDelay

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

Introduction

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

Prototype

public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay,
        TimeUnit unit);

Source Link

Document

Submits a periodic action that becomes enabled first after the given initial delay, and subsequently with the given delay between the termination of one execution and the commencement of the next.

Usage

From source file:org.janusgraph.TestBed.java

/**
 * @param args/*from  w  w w  .ja v a 2s  .  c  o m*/
 * @throws java.io.IOException
 */
public static void main(String[] args) throws Exception {
    Method method = TestBed.class.getMethod("getInt", int.class, int.class);
    AnnotatedType rt = method.getAnnotatedReturnType();
    System.out.println(rt.getType());
    System.out.println(rt.getAnnotations().length);
    System.out.println(method.getAnnotations().length);
    for (int i = 0; i < method.getAnnotations().length; i++) {
        System.out.println(method.getAnnotations()[i]);
    }

    //        String[] s = {"a","b","c","d","e","f","g","h","i","x","u"};
    //        int len = s.length;
    //        Random random = new Random();
    //
    //        Context c = new Context(new ObserverManager(),Observer.NO_OP);
    //        //Warmup
    //        for (int i = 0; i < 1000000000; i++) {
    //            c.observe(s[1],s[2]);
    //        }
    //        long before = System.nanoTime();
    //        for (int i = 0; i < 1000000000; i++) {
    //            c.observe(s[1],s[2]);
    //        }
    //        long total = System.nanoTime()-before;
    //        System.out.println("Total time: " + total/1000000);

    System.exit(0);

    final ScheduledExecutorService exe = new ScheduledThreadPoolExecutor(1, new RejectedExecutionHandler() {
        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            r.run();
        }
    });
    ScheduledFuture future = exe.scheduleWithFixedDelay(new Runnable() {
        AtomicInteger atomicInt = new AtomicInteger(0);

        @Override
        public void run() {
            try {
                for (int i = 0; i < 10; i++) {
                    exe.submit(new Runnable() {

                        private final int number = atomicInt.incrementAndGet();

                        @Override
                        public void run() {
                            try {
                                Thread.sleep(150);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            System.out.println(number);
                        }
                    });
                    System.out.println("Submitted: " + i);
                    //                    doSomethingExpensive(20);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }, 0, 1, TimeUnit.SECONDS);
    Thread.sleep(10000);
    //        future.get(1,TimeUnit.SECONDS);
    System.out.println("Cancel: " + future.cancel(false));
    System.out.println("Done: " + future.isDone());
    exe.shutdown();
    //        Thread.sleep(2000);
    System.out.println("Terminate: " + exe.awaitTermination(5, TimeUnit.SECONDS));
    System.out.println("DONE");
    NonBlockingHashMapLong<String> id1 = new NonBlockingHashMapLong<String>(128);
    ConcurrentHashMap<Long, String> id2 = new ConcurrentHashMap<Long, String>(128, 0.75f, 2);

}

From source file:com.laudandjolynn.mytv.Main.java

/**
 * ?/*from w w  w. j a v a2s . c  o m*/
 * 
 * @param data
 * @param tvService
 */
private static void createEverydayCron(final MyTvData data, final TvService tvService) {
    ScheduledExecutorService scheduled = new ScheduledThreadPoolExecutor(3,
            new BasicThreadFactory.Builder().namingPattern("Mytv_Scheduled_Task").build());
    Date today = new Date();
    String nextWeek = DateUtils.date2String(DateUtils.nextWeek(today), "yyyy-MM-dd 00:01:00");
    long crawlTaskInitDelay = (DateUtils.string2Date(nextWeek).getTime() - today.getTime()) / 1000;
    logger.info("cron crawler task will be automatic start after " + crawlTaskInitDelay + " seconds at "
            + nextWeek);
    scheduled.scheduleWithFixedDelay(new Runnable() {

        @Override
        public void run() {
            Date[] weeks = DateUtils.getWeek(new Date());
            logger.info("begin to crawl program table of " + Arrays.deepToString(weeks));
            ExecutorService executorService = Executors.newFixedThreadPool(Constant.CPU_PROCESSOR_NUM,
                    new BasicThreadFactory.Builder().namingPattern("Mytv_Schedule_Crawl_Program_Table_%d")
                            .build());
            List<TvStation> stationList = tvService.getDisplayedTvStation();
            for (Date date : weeks) {
                crawlAllProgramTable(stationList, executorService, DateUtils.date2String(date, "yyyy-MM-dd"),
                        tvService);
            }
            executorService.shutdown();
        }
    }, crawlTaskInitDelay, 604860, TimeUnit.SECONDS);

    // ??
    String nextDate = DateUtils.tommorow() + " 23:00:00";
    long commonInitDelay = (DateUtils.string2Date(nextDate).getTime() - today.getTime()) / 1000;
    logger.info("cron refresh proxy task will be automatic start after " + commonInitDelay + " seconds at "
            + nextDate);
    scheduled.scheduleWithFixedDelay(new Runnable() {

        @Override
        public void run() {
            logger.info("begin to refresh proxies.");
            MyTvProxyManager.getInstance().refresh();
        }
    }, commonInitDelay, 86400, TimeUnit.SECONDS);

    // 
    logger.info("cron refresh cache task will be automatic start after " + commonInitDelay + " seconds at "
            + nextDate);
    scheduled.scheduleWithFixedDelay(new Runnable() {

        @Override
        public void run() {
            logger.info("begin to refresh caches.");
            makeCache(tvService);
        }
    }, commonInitDelay, 86400, TimeUnit.SECONDS);

    // scheduled?????
    // scheduled.shutdown();
}

From source file:org.wso2.carbon.suicide.internal.SuicideActivator.java

public void start(BundleContext context) {
    try {// w  ww .j  a v a 2 s .c  o m
        ScheduledExecutorService suicideScheduler = Executors.newScheduledThreadPool(1);
        suicideScheduler.scheduleWithFixedDelay(new SuicideTask(), 30, 30, TimeUnit.SECONDS);
    } catch (Throwable e) {
        log.error("Cannot start SuicideActivator", e);
    }
}

From source file:org.wso2.iot.refarch.rpi.agent.Receiver.java

private void start() {
    ScheduledExecutorService dhtReaderScheduler = Executors.newScheduledThreadPool(1);
    dhtReaderScheduler.scheduleWithFixedDelay(new MonitoringTask(), 0, 10, TimeUnit.SECONDS);
}

From source file:org.wso2.iot.refarch.rpi.agent.Publisher.java

private void start(int updateInterval) {
    ScheduledExecutorService dhtReaderScheduler = Executors.newScheduledThreadPool(1);
    dhtReaderScheduler.scheduleWithFixedDelay(new MonitoringTask(dhtSensor), 0, updateInterval,
            TimeUnit.SECONDS);// ww  w .j a v a2  s .  c o m
}

From source file:com.spotify.helios.master.DeadAgentReaper.java

@Override
protected ScheduledFuture<?> schedule(final Runnable runnable, final ScheduledExecutorService executorService) {
    return executorService.scheduleWithFixedDelay(runnable, 0, INTERVAL, INTERVAL_TIME_UNIT);
}

From source file:com.netflix.conductor.core.execution.WorkflowSweeper.java

public void init(WorkflowExecutor workflowProvider) {

    ScheduledExecutorService deciderPool = Executors.newScheduledThreadPool(1);

    deciderPool.scheduleWithFixedDelay(() -> {

        try {//from w ww  .ja v a2 s  .  c  om

            if (config.disableSweep()) {
                logger.info("Workflow sweep is disabled.");
                return;
            }
            List<String> workflowIds = queues.pop(WorkflowExecutor.deciderQueue, 2 * executorThreadPoolSize,
                    2000);
            sweep(workflowIds, workflowProvider);

        } catch (Exception e) {
            Monitors.error(className, "sweep");
            logger.error(e.getMessage(), e);

        }

    }, 500, 500, TimeUnit.MILLISECONDS);
}

From source file:it.crs4.pydoop.mapreduce.pipes.TaskLog.java

public static ScheduledExecutorService createLogSyncer() {
    final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
        @Override/*  w  w  w.ja  v  a  2  s.  com*/
        public Thread newThread(Runnable r) {
            final Thread t = Executors.defaultThreadFactory().newThread(r);
            t.setDaemon(true);
            t.setName("Thread for syncLogs");
            return t;
        }
    });
    ShutdownHookManager.get().addShutdownHook(new Runnable() {
        @Override
        public void run() {
            TaskLog.syncLogsShutdown(scheduler);
        }
    }, 50);
    scheduler.scheduleWithFixedDelay(new Runnable() {
        @Override
        public void run() {
            TaskLog.syncLogs();
        }
    }, 0L, 5L, TimeUnit.SECONDS);
    return scheduler;
}

From source file:io.fabric8.che.starter.openshift.CheDeploymentConfig.java

private void waitUntilDeploymentConfigIsAvailable(final OpenShiftClient client, String namespace) {
    final BlockingQueue<Object> queue = new ArrayBlockingQueue<Object>(1);

    final Runnable readinessPoller = new Runnable() {
        public void run() {
            try {
                if (isDeploymentAvailable(client, namespace)) {
                    queue.put(true);// w  ww .  j a v  a2  s  .  c o  m
                    return;
                } else {
                    queue.put(false);
                    return;
                }
            } catch (Throwable t) {
                try {
                    if (queue.isEmpty()) {
                        queue.put(false);
                    }
                    return;
                } catch (InterruptedException e) {
                }
            }
        }
    };

    ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
    ScheduledFuture<?> poller = executor.scheduleWithFixedDelay(readinessPoller, 0, 500, TimeUnit.MILLISECONDS);
    executor.schedule(new Runnable() {

        @Override
        public void run() {
            poller.cancel(true);
        }
    }, Integer.valueOf(startTimeout), TimeUnit.SECONDS);
    try {
        while (!waitUntilReady(queue)) {
        }
    } finally {
        if (!poller.isDone()) {
            poller.cancel(true);
        }
        executor.shutdown();
    }
}

From source file:org.wso2.iot.refarch.rpi.agent.Agent.java

private void run() {
    ScheduledExecutorService dhtReaderScheduler = Executors.newScheduledThreadPool(1);
    dhtReaderScheduler.scheduleWithFixedDelay(new MonitoringDeamon(), 0, 10, TimeUnit.SECONDS);
}