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:com.janrain.backplane.config.BackplaneConfig.java

private Pair<String, ExecutorService> createPingTask() {
    final String label = "redis/jedis";
    ScheduledExecutorService ping = Executors.newScheduledThreadPool(1);
    ping.scheduleWithFixedDelay(new Runnable() {
        @Override/* www .  j  av a 2 s.c o m*/
        public void run() {
            com.janrain.redis.Redis.getInstance().ping(label);
        }
    }, 30, 10, TimeUnit.SECONDS);
    return new Pair<String, ExecutorService>(label, ping);
}

From source file:colt.nicity.performance.agent.LatentHttpPump.java

public void start() {
    ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
    scheduledExecutorService.scheduleWithFixedDelay(() -> {
        try {//from   w w w. j av a2 s . com
            final long now = System.currentTimeMillis();
            Boolean enabled = latency.getLatentGraph(this.enabled.get()).latentDepths((from, to) -> {
                // TODO batching
                try {
                    JSONObject sample = new JSONObject();
                    sample.put("clusterName", clusterName);
                    sample.put("serviceName", serviceName);
                    sample.put("serviceVersion", serviceVersion);
                    sample.put("sampleTimestampEpochMillis", now);
                    sample.put("from", latentJson(from));
                    sample.put("to", latentJson(to));
                    HttpResponse postJson = httpClient.postJson("/profile/latents", sample.toJSONString());
                    if (postJson.getStatusCode() >= 200 && postJson.getStatusCode() < 300) {
                        String response = new String(postJson.getResponseBody());
                        return Boolean.getBoolean(response);
                    } else {
                        return null;
                    }
                } catch (Exception x) {
                    //if (verbose) {
                    //System.out.println("Latent Service is inaccessible. "+x.getMessage());
                    //}
                    return null;
                }

            });

            if (enabled != null) {
                this.enabled.set(enabled);
            }

        } catch (Throwable t) {
            t.printStackTrace();
        }
    }, 5, 5, TimeUnit.SECONDS);
}

From source file:com.ctrip.infosec.rule.executor.ModelRulesExecutorService.java

@PostConstruct
public void dequeue() {
    int threads = 1;
    ExecutorService executor = Executors.newFixedThreadPool(threads);
    for (int i = 0; i < threads; i++) {
        executor.submit(new Runnable() {
            @Override//  www  .  j av  a 2  s.co m
            public void run() {
                while (true) {
                    RiskFact fact = null;
                    beforeInvoke("ModelRules.execute");
                    try {
                        fact = queue.take();
                        TraceLogger.beginTrans(fact.eventId);
                        TraceLogger.setParentTransId(
                                valueAsString(fact.ext, Constants.key_traceLoggerParentTransId));
                        fact.ext.remove(Constants.key_traceLoggerParentTransId);
                        execute(fact);
                    } catch (Exception ex) {
                        fault("ModelRules.execute");
                        logger.error("dequeue exception.", ex);
                    } finally {
                        afterInvoke("ModelRules.execute");
                        if (fact != null) {
                            TraceLogger.commitTrans();
                        }
                        Threads.sleep(10, TimeUnit.MILLISECONDS);
                    }
                }
            }
        });
    }
    ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
    scheduler.scheduleWithFixedDelay(new Runnable() {
        @Override
        public void run() {
            int size = queue.size();
            if (size > 0) {
                SarsMqStatRepository.put("MODEL_EXECUTE_QUEUE", size);
                logger.warn("queue size: " + size);
            }
            int max = 10000;
            if (size > max) {
                do {
                    RiskFact fact = queue.poll();
                    logger.warn("model queue is full. drop message: " + fact.eventId);
                } while (queue.size() > max);
            }
        }
    }, 30, 30, TimeUnit.SECONDS);
}

From source file:org.openmrs.module.xdsbrepository.XDSbRepositoryInterfaceActivator.java

/**
 * @see ModuleActivator#started()//w  ww.  j av a  2  s. c  o  m
 */
public void started() {
    XDSAudit.setAuditLogger(Context.getService(AtnaAuditService.class).getLogger());
    XDSAudit.logApplicationActivity(AtnaConfiguration.getInstance().getDeviceName(),
            EventTypeCode.ApplicationStart, true);
    log.info("XDSb Repository Interface Module started");

    AdministrationService as = Context.getAdministrationService();
    boolean async = Boolean
            .parseBoolean(as.getGlobalProperty(XDSbServiceConstants.XDS_REPOSITORY_DISCRETE_HANDLER_ASYNC));
    int pollPeriod = Integer.parseInt(Context.getAdministrationService()
            .getGlobalProperty(XDSbServiceConstants.XDS_REPOSITORY_DISCRETE_HANDLER_ASYNC_POLL_PERIOD, "100"));

    if (async) {
        Integer maxTasks = Integer.parseInt(
                as.getGlobalProperty(XDSbServiceConstants.XDS_REPOSITORY_DISCRETE_HANDLER_ASYNC_MAX_TASKS));
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(maxTasks);
        // for each thread schedule a recurring task
        for (int i = 0; i < maxTasks; i++) {
            scheduledExecutorService.scheduleWithFixedDelay(new DiscreteDataProcessorTask(), pollPeriod,
                    pollPeriod, TimeUnit.MILLISECONDS);
        }
    }
}

From source file:be.vlaanderen.sesam.monitor.internal.util.ThreadPoolTaskScheduler.java

public ScheduledFuture scheduleWithFixedDelay(Runnable task, long delay) {
    ScheduledExecutorService executor = getScheduledExecutor();
    try {//  w  w  w  .  j av a 2s  . c  om
        return executor.scheduleWithFixedDelay(errorHandlingTask(task, true), 0, delay, TimeUnit.MILLISECONDS);
    } catch (RejectedExecutionException ex) {
        throw new TaskRejectedException("Executor [" + executor + "] did not accept task: " + task, ex);
    }
}

From source file:com.janrain.backplane2.server.config.Backplane2Config.java

private ScheduledExecutorService createPingTask() {
    ScheduledExecutorService ping = Executors.newScheduledThreadPool(1);
    ping.scheduleWithFixedDelay(new Runnable() {
        @Override//  ww  w  .j  a va 2 s .c  o m
        public void run() {
            com.janrain.redis.Redis.getInstance().ping();
        }
    }, 30, 10, TimeUnit.SECONDS);
    return ping;
}

From source file:com.btoddb.chronicle.plunkers.HdfsPlunkerImplIT.java

@Test
@Ignore("very flakey, need to work out a more stable way of testing")
public void testLongRun() throws Exception {
    plunker.setIdleTimeout(0);/*from   w w w.j av a  2s  .c o  m*/
    plunker.setRollPeriod(2);
    plunker.setTimeoutCheckPeriod(100);
    plunker.init(config);

    final int sleep = 200;
    final int maxCount = 100; // 20 seconds at 'sleep' interval should be 10 files
    final AtomicInteger count = new AtomicInteger();

    // do this to prime HDFS FileSystem object - otherwise timing is off
    plunker.handleInternal(Arrays.asList(new Event("the-body").withHeader("customer", "cust")
            .withHeader("msgId", String.valueOf(count.getAndIncrement()))));

    ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
    System.out.println("start");
    executor.scheduleWithFixedDelay(new Runnable() {
        @Override
        public void run() {
            try {
                System.out.println("time = " + System.currentTimeMillis());
                plunker.handleInternal(Arrays.asList(new Event("the-body").withHeader("customer", "cust")
                        .withHeader("msgId", String.valueOf(count.get()))));
            } catch (Exception e) {
                e.printStackTrace();
            }

            count.incrementAndGet();
        }
    }, 0, sleep, TimeUnit.MILLISECONDS);

    while (count.get() < maxCount) {
        Thread.sleep(sleep / 2);
    }

    executor.shutdown();
    executor.awaitTermination(60, TimeUnit.SECONDS);

    Thread.sleep(1500);

    plunker.shutdown();

    Event[] events = new Event[count.get()];
    for (int i = 0; i < count.get(); i++) {
        events[i] = new Event("the-body").withHeader("customer", "cust").withHeader("msgId", String.valueOf(i));
    }

    File theDir = new File(String.format("%s/the/cust/path", baseDir.getPath()));

    assertThat(theDir, ftUtils.countWithSuffix(".tmp", 0));
    assertThat(theDir, ftUtils.countWithSuffix(".avro", 10));

    assertThat(theDir, ftUtils.hasEventsInDir(events));
}

From source file:net.sourceforge.subsonic.ajax.ChatService.java

/**
 * Invoked by Spring.//from www . j a v a 2s  . c  o  m
 */
public void init() {
    // Delete old messages every hour.
    ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
    Runnable runnable = new Runnable() {
        public void run() {
            removeOldMessages();
        }
    };
    executor.scheduleWithFixedDelay(runnable, 0L, 3600L, TimeUnit.SECONDS);
}

From source file:at.wada811.android.library.demos.concurrent.ExecutorActivity.java

/**
 * {@link ScheduledExecutorService#scheduleWithFixedDelay(Runnable, long, long, TimeUnit)}
 * ?????//from  w  w  w  .ja  v a2s.  c o  m
 * 
 * <p>
 * ??????????????????????
 * </p>
 */
public void newSingleThreadScheduledExecutorWithFixedDelayTest() {
    LogUtils.d();
    ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
    executorService.scheduleWithFixedDelay(new ExecutorRunnable("A", 1), 1, 2, TimeUnit.SECONDS);
    shutdown(executorService);
}

From source file:at.wada811.android.library.demos.concurrent.ExecutorActivity.java

/**
 * {@link ScheduledExecutorService#scheduleWithFixedDelay(Runnable, long, long, TimeUnit)}
 * ???/*from  ww  w.  ja  v a2  s.  c om*/
 * 
 * <p>
 * ?????????????????????? <br>
 * ????????????????????
 * </p>
 */
public void newSingleThreadScheduledExecutorWithFixedDelayDuringExecutionTest() {
    LogUtils.d();
    ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
    executorService.scheduleWithFixedDelay(new ExecutorRunnable("A", 3), 1, 2, TimeUnit.SECONDS);
    shutdown(executorService);
}