Example usage for java.util.concurrent ScheduledThreadPoolExecutor scheduleWithFixedDelay

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

Introduction

In this page you can find the example usage for java.util.concurrent ScheduledThreadPoolExecutor 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.btoddb.chronicle.plunkers.HdfsPlunkerImplTest.java

@Test
public void testInit(@Injectable final ScheduledThreadPoolExecutor closeExec, // don't want other executors affected
        @Injectable final ScheduledThreadPoolExecutor idleExec // don't want other executors affected
) throws Exception {
    new Expectations() {
        {/*from   w  ww. j av  a  2  s  . c o m*/
            idleExec.scheduleWithFixedDelay((Runnable) any, 10000, 10000, TimeUnit.MILLISECONDS);
            times = 1;
        }
    };
    plunker.setCloseExec(closeExec);
    plunker.setIdleTimerExec(idleExec);
    plunker.init(config);
}

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

@Test
public void testShutdown(@Injectable final ScheduledThreadPoolExecutor closeExec, // don't want other executors affected
        @Injectable final ScheduledThreadPoolExecutor idleExec // don't want other executors affected
) throws Exception {
    new Expectations() {
        {// w  ww  . j ava  2  s  .co  m
            idleExec.scheduleWithFixedDelay((Runnable) any, 10000, 10000, TimeUnit.MILLISECONDS);
            times = 1;
            idleExec.shutdown();
            times = 1;
            closeExec.shutdown();
            times = 1;
            closeExec.awaitTermination(plunker.getShutdownWaitTimeout(), TimeUnit.SECONDS);
            times = 1;
            result = true;
        }
    };
    plunker.setCloseExec(closeExec);
    plunker.setIdleTimerExec(idleExec);
    plunker.init(config);
    plunker.shutdown();
}

From source file:org.cerberus.launchcampaign.checkcampaign.CheckCampaignStatus.java

/**
 * Check all 5 seconds the status of campaign's execution. 
 * @param checkCampaign call method checkCampaign() all 5 seconds with parameter {@link ResultCIDto}.  
 *                   {@link ResultCIDto} contains all information of execution of campaing at the instant t
 * @param result call method result() when campaign execution is finish.
 *             {@link ResultCIDto} contains all information of execution at finish time
 * @throws Exception // ww  w.  jav  a2  s  .c  o m
 */
public void execute(final CheckCampaignEvent checkCampaign, final ResultEvent result, final LogEvent logEvent)
        throws Exception {
    final ScheduledThreadPoolExecutor sch = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(1);

    final AtomicReference<Exception> exceptionOnThread = new AtomicReference<Exception>();

    sch.scheduleWithFixedDelay(new Runnable() {

        @Override
        public void run() {
            try {
                URL resultURL = new URL(urlCerberus + "/" + Constantes.URL_RESULT_CI + "?tag=" + tagCerberus);
                ResultCIDto resultDto = new ObjectMapper().readValue(resultURL, ResultCIDto.class);

                // condition to finish task
                if (!"PE".equals(resultDto.getResult())) {
                    result.result(resultDto);
                    sch.shutdown(); // when campaign is finish, we shutdown the schedule thread
                }

                if (!checkCampaign.checkCampaign(resultDto)) {
                    sch.shutdown();
                }
            } catch (SocketException e) {
                // do nothing during network problem. Wait the timeout to shutdown, and notify the error to logEvent
                logEvent.log("", e.getMessage() + "\n" + ExceptionUtils.getStackTrace(e));
            } catch (Exception e) {
                exceptionOnThread.set(e);
                sch.shutdown();
            }
        }
    }, 0, this.timeToRefreshCampaignStatus, TimeUnit.SECONDS);

    sch.awaitTermination(this.timeoutForCampaignExecution, TimeUnit.SECONDS);

    // pass exeption of thread to called method
    if (exceptionOnThread.get() != null) {
        throw exceptionOnThread.get();
    }
}

From source file:org.apache.falcon.service.EntitySLAMonitoringService.java

@Override
public void init() throws FalconException {

    String freq = StartupProperties.get().getProperty("entity.sla.statusCheck.frequency.seconds", "600");
    statusCheckFrequencySeconds = Integer.parseInt(freq);

    freq = StartupProperties.get().getProperty("entity.sla.lookAheadWindow.millis", "900000");
    lookAheadWindowMillis = Integer.parseInt(freq);
    ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
    addPendingEntityInstances(now());//from w w  w.  ja va  2s .  c om
    executor.scheduleWithFixedDelay(new Monitor(), 0, statusCheckFrequencySeconds, TimeUnit.SECONDS);
}

From source file:org.apache.falcon.service.FeedSLAMonitoringService.java

@Override
public void init() throws FalconException {
    String uri = StartupProperties.get().getProperty("feed.sla.service.store.uri");
    storePath = new Path(uri);
    filePath = new Path(storePath, "feedSLAMonitoringService");
    fileSystem = initializeFileSystem();

    String freq = StartupProperties.get().getProperty("feed.sla.serialization.frequency.millis", ONE_HOUR);
    serializationFrequencyMillis = Integer.valueOf(freq);

    freq = StartupProperties.get().getProperty("feed.sla.statusCheck.frequency.seconds", "600");
    statusCheckFrequencySeconds = Integer.valueOf(freq);

    freq = StartupProperties.get().getProperty("feed.sla.lookAheadWindow.millis", "900000");
    lookAheadWindowMillis = Integer.valueOf(freq);

    String size = StartupProperties.get().getProperty("feed.sla.queue.size", "288");
    queueSize = Integer.valueOf(size);

    try {/*from   w w w.  java  2  s. c o  m*/
        if (fileSystem.exists(filePath)) {
            deserialize(filePath);
        } else {
            LOG.debug("No old state exists at: {}, Initializing a clean state.", filePath.toString());
            initializeService();
        }
    } catch (IOException e) {
        throw new FalconException("Couldn't check the existence of " + filePath, e);
    }
    ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
    executor.scheduleWithFixedDelay(new Monitor(), 0, statusCheckFrequencySeconds, TimeUnit.SECONDS);
}

From source file:org.codinjutsu.tools.jenkins.view.BrowserPanel.java

public void initScheduledJobs() {
    final ExecutorService executorService = ExecutorService.getInstance(project);
    final ScheduledThreadPoolExecutor executor = executorService.getExecutor();
    executorService.safeTaskCancel(refreshViewFutureTask);
    executor.remove(refreshViewJob);/*from www  . j  a  va 2  s .  c o m*/

    if (jenkinsAppSettings.isServerUrlSet() && jenkinsAppSettings.getJobRefreshPeriod() > 0) {
        refreshViewFutureTask = executor.scheduleWithFixedDelay(refreshViewJob,
                jenkinsAppSettings.getJobRefreshPeriod(), jenkinsAppSettings.getJobRefreshPeriod(),
                TimeUnit.MINUTES);
    }
}

From source file:org.opendaylight.genius.utils.batching.ResourceBatchingManager.java

public void registerBatchableResource(String resourceType, final BlockingQueue<ActionableResource> resQueue,
        final ResourceHandler resHandler) {
    Preconditions.checkNotNull(resQueue, "ResourceQueue to use for batching cannot not be null.");
    Preconditions.checkNotNull(resHandler, "ResourceHandler cannot not be null.");
    if (resourceHandlerMapper.contains(resourceType)) {
        throw new RuntimeException("Resource type already registered");
    }/*from  w  w w.  ja va  2  s .  c om*/
    resourceHandlerMapper.put(resourceType, new ImmutablePair<>(resQueue, resHandler));
    ScheduledThreadPoolExecutor resDelegatorService = (ScheduledThreadPoolExecutor) Executors
            .newScheduledThreadPool(1, ThreadFactoryProvider.builder().namePrefix("ResourceBatchingManager")
                    .logger(LOG).build().get());
    resourceBatchingThreadMapper.put(resourceType, resDelegatorService);
    LOG.info("Registered resourceType {} with batchSize {} and batchInterval {}", resourceType,
            resHandler.getBatchSize(), resHandler.getBatchInterval());
    if (resDelegatorService.getPoolSize() == 0) {
        resDelegatorService.scheduleWithFixedDelay(new Batcher(resourceType), INITIAL_DELAY,
                resHandler.getBatchInterval(), TIME_UNIT);
    }
}