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:io.fabric8.kubernetes.client.dsl.internal.RollingUpdater.java

/**
 * Since k8s v1.4.x, rc/rs deletes are asynchronous.
 * Lets wait until the resource is actually deleted in the server
 *//*w w  w . j  a  v a  2s  .c o  m*/
private void waitUntilDeleted(final String namespace, final String name) {
    final CountDownLatch countDownLatch = new CountDownLatch(1);

    final Runnable waitTillDeletedPoller = new Runnable() {
        public void run() {
            try {
                T res = resources().inNamespace(namespace).withName(name).get();
                if (res == null) {
                    countDownLatch.countDown();
                }
            } catch (KubernetesClientException e) {
                if (e.getCode() == 404) {
                    countDownLatch.countDown();
                }
            }
        }
    };

    ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
    ScheduledFuture poller = executor.scheduleWithFixedDelay(waitTillDeletedPoller, 0, 5, TimeUnit.SECONDS);
    ScheduledFuture logger = executor.scheduleWithFixedDelay(new Runnable() {
        @Override
        public void run() {
            LOG.debug("Found resource {}/{} not yet deleted on server, so waiting...", namespace, name);
        }
    }, 0, loggingIntervalMillis, TimeUnit.MILLISECONDS);
    try {
        countDownLatch.await(DEFAULT_SERVER_GC_WAIT_TIMEOUT, TimeUnit.MILLISECONDS);
        executor.shutdown();
    } catch (InterruptedException e) {
        poller.cancel(true);
        logger.cancel(true);
        executor.shutdown();
        LOG.warn("Still found deleted resource {} in namespace: {}  after waiting for {} seconds so giving up",
                name, namespace, TimeUnit.MILLISECONDS.toSeconds(DEFAULT_SERVER_GC_WAIT_TIMEOUT));
    }
}

From source file:io.fabric8.kubernetes.client.dsl.internal.RollingUpdater.java

/**
 * Lets wait until there are enough Ready pods of the given RC
 *//*from  ww w . j ava  2 s.c  o  m*/
private void waitUntilPodsAreReady(final T obj, final String namespace, final int requiredPodCount) {
    final CountDownLatch countDownLatch = new CountDownLatch(1);
    final AtomicInteger podCount = new AtomicInteger(0);

    final Runnable readyPodsPoller = new Runnable() {
        public void run() {
            PodList podList = listSelectedPods(obj);
            int count = 0;
            List<Pod> items = podList.getItems();
            for (Pod item : items) {
                for (PodCondition c : item.getStatus().getConditions()) {
                    if (c.getType().equals("Ready") && c.getStatus().equals("True")) {
                        count++;
                    }
                }
            }
            podCount.set(count);
            if (count == requiredPodCount) {
                countDownLatch.countDown();
            }
        }
    };

    ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
    ScheduledFuture poller = executor.scheduleWithFixedDelay(readyPodsPoller, 0, 1, TimeUnit.SECONDS);
    ScheduledFuture logger = executor.scheduleWithFixedDelay(new Runnable() {
        @Override
        public void run() {
            LOG.debug("Only {}/{} pod(s) ready for {}: {} in namespace: {} seconds so waiting...",
                    podCount.get(), requiredPodCount, obj.getKind(), obj.getMetadata().getName(), namespace);
        }
    }, 0, loggingIntervalMillis, TimeUnit.MILLISECONDS);
    try {
        countDownLatch.await(rollingTimeoutMillis, TimeUnit.MILLISECONDS);
        executor.shutdown();
    } catch (InterruptedException e) {
        poller.cancel(true);
        logger.cancel(true);
        executor.shutdown();
        LOG.warn(
                "Only {}/{} pod(s) ready for {}: {} in namespace: {}  after waiting for {} seconds so giving up",
                podCount.get(), requiredPodCount, obj.getKind(), obj.getMetadata().getName(), namespace,
                TimeUnit.MILLISECONDS.toSeconds(rollingTimeoutMillis));
    }
}

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

public ScheduledFuture scheduleWithFixedDelay(Runnable task, Date startTime, long delay) {
    ScheduledExecutorService executor = getScheduledExecutor();
    long initialDelay = startTime.getTime() - System.currentTimeMillis();
    try {//  w w w.  j  a  v a 2 s  .c o  m
        return executor.scheduleWithFixedDelay(errorHandlingTask(task, true), initialDelay, delay,
                TimeUnit.MILLISECONDS);
    } catch (RejectedExecutionException ex) {
        throw new TaskRejectedException("Executor [" + executor + "] did not accept task: " + task, ex);
    }
}

From source file:org.apache.pulsar.functions.worker.SchedulerManager.java

private void scheduleCompaction(ScheduledExecutorService executor, long scheduleFrequencySec) {
    if (executor != null) {
        executor.scheduleWithFixedDelay(() -> {
            if (membershipManager.isLeader() && isCompactionNeeded.get()) {
                compactAssignmentTopic();
                isCompactionNeeded.set(false);
            }//from w  w w.  j av  a2s . c o  m
        }, scheduleFrequencySec, scheduleFrequencySec, TimeUnit.SECONDS);
    }
}

From source file:org.onosproject.incubator.rpc.grpc.LinkProviderServiceServerProxy.java

LinkProviderServiceServerProxy(GrpcRemoteServiceServer server) {
    this.server = checkNotNull(server);
    ScheduledExecutorService executor = server.getSharedExecutor();
    lastSeen = CacheBuilder.newBuilder().expireAfterWrite(EVICT_LIMIT, TimeUnit.SECONDS)
            .removalListener(asynchronous(this::onRemove, executor)).build();

    executor.scheduleWithFixedDelay(lastSeen::cleanUp, EVICT_LIMIT, EVICT_LIMIT, TimeUnit.SECONDS);
}

From source file:cf.service.ServiceGarbageCollector.java

public ServiceGarbageCollector(ScheduledExecutorService executorService, UUID serviceGuid,
        CloudController cloudController, TokenProvider token, Provisioner provisioner) {
    this.serviceGuid = serviceGuid;
    this.cloudController = cloudController;
    this.token = token;
    this.provisioner = provisioner;
    executorService.scheduleWithFixedDelay(new Runnable() {
        @Override//  w w  w.java 2s. co  m
        public void run() {
            collect();
        }
    }, COLLECTION_RATE, COLLECTION_RATE, TimeUnit.MILLISECONDS);
}

From source file:org.apache.axis2.clustering.tribes.MembershipManager.java

public void setupStaticMembershipManagement(StaticMembershipInterceptor staticMembershipInterceptor) {
    this.staticMembershipInterceptor = staticMembershipInterceptor;
    ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    scheduler.scheduleWithFixedDelay(new MemberListSenderTask(), 5, 5, TimeUnit.SECONDS);
}

From source file:com.turbospaces.spaces.SpaceReceiveAdapter.java

@Override
public void afterPropertiesSet() {
    ScheduledExecutorService scheduledExecutorService = jSpace.getSpaceConfiguration()
            .getScheduledExecutorService();
    cleaupFuture = scheduledExecutorService.scheduleWithFixedDelay(new Runnable() {
        @Override/*from w w w.  ja va  2 s .c  o  m*/
        public void run() {
            if (!durableTransactions.isEmpty()) {
                Collection<Cache<Long, SpaceTransactionHolder>> values = durableTransactions.values();
                for (Cache<Long, SpaceTransactionHolder> cache : values) {
                    logger.debug("running automatic cleanup of dead transaction for {}", cache);
                    cache.cleanUp();
                }
            }
        }
    }, 0, jSpace.getSpaceConfiguration().getCacheCleanupPeriod(), TimeUnit.MILLISECONDS);
}

From source file:org.apache.nifi.registry.provider.flow.git.GitFlowMetaData.java

void startPushThread() {
    // If successfully loaded, start pushing thread if necessary.
    if (isEmpty(remoteToPush)) {
        return;//from  w  w w. j  a  v a2s  .co  m
    }

    final ThreadFactory threadFactory = new BasicThreadFactory.Builder().daemon(true)
            .namingPattern(getClass().getSimpleName() + " Push thread").build();

    // Use scheduled fixed delay to control the minimum interval between push activities.
    // The necessity of executing push is controlled by offering messages to the pushQueue.
    // If multiple commits are made within this time window, those are pushed by a single push execution.
    final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(threadFactory);
    executorService.scheduleWithFixedDelay(() -> {

        final Long offeredTimestamp;
        try {
            offeredTimestamp = pushQueue.take();
        } catch (InterruptedException e) {
            logger.warn("Waiting for push request has been interrupted due to {}", e.getMessage(), e);
            return;
        }

        logger.debug("Took a push request sent at {} to {}...", offeredTimestamp, remoteToPush);
        final PushCommand pushCommand = new Git(gitRepo).push().setRemote(remoteToPush);
        if (credentialsProvider != null) {
            pushCommand.setCredentialsProvider(credentialsProvider);
        }

        try {
            final Iterable<PushResult> pushResults = pushCommand.call();
            for (PushResult pushResult : pushResults) {
                logger.debug(pushResult.getMessages());
            }
        } catch (GitAPIException e) {
            logger.error(format("Failed to push commits to %s due to %s", remoteToPush, e), e);
        }

    }, 10, 10, TimeUnit.SECONDS);
}

From source file:com.brienwheeler.lib.concurrent.ExecutorsTest.java

@Test
public void testNewSingleThreadScheduledExecutor() {
    NamedThreadFactory threadFactory = new NamedThreadFactory(THREAD_FACTORY_NAME);
    ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(threadFactory);

    ScheduledFuture<?> future1 = executor.schedule(new NullRunnable(), 10, TimeUnit.MILLISECONDS);
    ScheduledFuture<Integer> future2 = executor.schedule(new IntCallable(1), 10, TimeUnit.MILLISECONDS);
    ScheduledFuture<?> future3 = executor.scheduleAtFixedRate(new NullRunnable(), 10, 10,
            TimeUnit.MILLISECONDS);
    ScheduledFuture<?> future4 = executor.scheduleWithFixedDelay(new NullRunnable(), 10, 10,
            TimeUnit.MILLISECONDS);

    List<Runnable> notRun = executor.shutdownNow();
    Assert.assertTrue(executor.isShutdown());
    Assert.assertEquals(4, notRun.size());
    Assert.assertTrue(CollectionUtils.containsInstance(notRun, future1));
    Assert.assertTrue(CollectionUtils.containsInstance(notRun, future2));
    Assert.assertTrue(CollectionUtils.containsInstance(notRun, future3));
    Assert.assertTrue(CollectionUtils.containsInstance(notRun, future4));
}