Example usage for java.util.concurrent ScheduledExecutorService schedule

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

Introduction

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

Prototype

public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit);

Source Link

Document

Submits a value-returning one-shot task that becomes enabled after the given delay.

Usage

From source file:com.github.joshelser.dropwizard.metrics.hadoop.StandaloneExample.java

/**
 * Runs a number of threads which generate metrics.
 *///  ww w.  j av  a2  s  .  c  o  m
public static void generateMetrics(final MetricRegistry metrics, final long metricsToGenerate, final int period,
        final TimeUnit periodTimeUnit, HadoopMetrics2Reporter metrics2Reporter, int numThreads)
        throws Exception {
    final ScheduledExecutorService pool = Executors.newScheduledThreadPool(numThreads);
    final CountDownLatch latch = new CountDownLatch(numThreads);

    for (int i = 0; i < numThreads; i++) {
        final int id = i;
        final int halfPeriod = (period / 2);
        Runnable task = new Runnable() {
            private long executions = 0;
            final Random r = new Random();

            @Override
            public void run() {
                if (executions >= metricsToGenerate) {
                    return;
                }
                metrics.counter("foo counter thread" + id).inc();
                executions++;
                if (executions < metricsToGenerate) {
                    pool.schedule(this, period + r.nextInt(halfPeriod), periodTimeUnit);
                } else {
                    latch.countDown();
                }
            }
        };
        pool.schedule(task, period, periodTimeUnit);
    }

    while (!latch.await(2, TimeUnit.SECONDS)) {
        metrics2Reporter.printQueueDebugMessage();
    }

    pool.shutdown();
    pool.awaitTermination(5000, TimeUnit.SECONDS);
}

From source file:com.networknt.client.oauth.OauthHelper.java

/**
 * renew the given Jwt jwt asynchronously.
 * When fail, it will swallow the exception, so no need return type to be handled by caller.
 * @param jwt the jwt you want to renew/* ww  w .ja  va 2 s .  c om*/
 */
private static void renewCCTokenAsync(final Jwt jwt) {
    // Not expired yet, try to renew async but let requests use the old token.
    logger.trace("In renew window but token is not expired yet.");
    if (!jwt.isRenewing() || System.currentTimeMillis() > jwt.getEarlyRetryTimeout()) {
        jwt.setRenewing(true);
        jwt.setEarlyRetryTimeout(System.currentTimeMillis() + jwt.getEarlyRefreshRetryDelay());
        logger.trace("Retrieve token async is called while token is not expired yet");

        ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

        executor.schedule(() -> {
            Result<Jwt> result = getCCTokenRemotely(jwt);
            if (result.isFailure()) {
                // swallow the exception here as it is on a best effort basis.
                logger.error("Async retrieve token error with status: {}", result.getError().toString());
            }
            //set renewing flag to false after response, doesn't matter if it's success or fail.
            jwt.setRenewing(false);
        }, 50, TimeUnit.MILLISECONDS);
        executor.shutdown();
    }
}

From source file:org.apache.ambari.servicemonitor.utils.KillHungProcess.java

public void start() {
    ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    future = scheduler.schedule(this, this.timeoutMilliseconds, TimeUnit.MILLISECONDS);
}

From source file:org.aludratest.cloud.selenium.impl.SeleniumHttpProxy.java

public static SeleniumHttpProxy create(int id, SeleniumResourceImpl resource, String prefix, long timeout,
        long maxIdleTime, String accessUrl, ScheduledExecutorService healthCheckExecutor) {
    URI oUri = URI.create(resource.getOriginalUrl());
    SeleniumHttpProxy proxy = new SeleniumHttpProxy(oUri.getScheme(), prefix, oUri.getHost(), oUri.getPort(),
            oUri.getPath());//  www.ja  v  a2 s.  co  m
    proxy.id = id;
    proxy.resource = resource;
    proxy.timeout = timeout;
    proxy.accessUrl = accessUrl;
    proxy.maxIdleTime = maxIdleTime;
    proxy.healthCheckClient = createHealthCheckHttpClient();
    proxy.healthCheckExecutor = healthCheckExecutor;

    // set resource to DISCONNECTED first
    resource.setState(ResourceState.DISCONNECTED);
    proxy.nextHealthCheck = healthCheckExecutor.schedule(proxy.checkStatusRunnable, 2000,
            TimeUnit.MILLISECONDS);

    return proxy;
}

From source file:com.bt.aloha.stack.QueuedSipMessageLatch.java

public QueuedSipMessageLatch(long aSequenceNumber, String aRequestMethod, long queuedSipMessageBlockingInterval,
        ScheduledExecutorService scheduledExecutorService) {
    super(1);//from  ww  w  .  j  a v a  2s.  c o  m
    sequenceNumber = aSequenceNumber;
    requestMethod = aRequestMethod;

    future = scheduledExecutorService.schedule(new Runnable() {
        public void run() {
            LOG.debug(String.format("Expiring queued message %d, method %s", sequenceNumber, requestMethod));
            countDown();
        }
    }, queuedSipMessageBlockingInterval, TimeUnit.MILLISECONDS);
}

From source file:org.codenergic.theskeleton.core.data.S3ClientConfig.java

@Bean
public ScheduledFuture<List<String>> createBuckets(MinioClient minioClient,
        ScheduledExecutorService executorService, S3ClientProperties clientProps) {
    return executorService.schedule(() -> clientProps.buckets.stream()
            .peek(bucket -> logger.info("Checking bucket [{}]", bucket.name)).peek(bucket -> {
                try {
                    if (!minioClient.bucketExists(bucket.name)) {
                        logger.info("Bucket doesn't exists, creating one");
                        minioClient.makeBucket(bucket.name);
                        logger.info("Bucket created");
                    } else {
                        logger.info("Bucket already exists");
                    }//from   w  w w. jav a2s.c  o m
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            })
            .peek(bucket -> bucket.getPolicies().stream().filter(Objects::nonNull)
                    .filter(policy -> Objects.nonNull(policy.policy))
                    .filter(policy -> StringUtils.isNotBlank(policy.prefix))
                    .peek(policy -> logger.info("Setting policy [{}] to bucket [{}] with prefix [{}]",
                            policy.policy, bucket.name, policy.prefix))
                    .forEach(policy -> {
                        try {
                            minioClient.setBucketPolicy(bucket.name, policy.prefix, policy.policy);
                        } catch (Exception e) {
                            logger.error(e.getMessage(), e);
                        }
                    }))
            .map(bucket -> bucket.name).collect(Collectors.toList()), 5, TimeUnit.SECONDS);
}

From source file:com.adaptris.core.jms.FailoverJmsProducerCase.java

public void testEventuallyConnects() throws Exception {
    final EmbeddedActiveMq broker = new EmbeddedActiveMq();
    FailoverJmsConnection connection = new FailoverJmsConnection();
    connection.addConnection(new JmsConnection(new BasicActiveMqImplementation("tcp://localhost:123456")));
    connection.addConnection(broker.getJmsConnection(new BasicActiveMqImplementation(), true));
    connection.setConnectionRetryInterval(new TimeInterval(250L, TimeUnit.MILLISECONDS));
    connection.addExceptionListener(new StandaloneConsumer());
    connection.setRegisterOwner(true);//ww w. ja v  a 2  s.  c om
    ScheduledExecutorService es = Executors.newSingleThreadScheduledExecutor();
    try {
        es.schedule(new Runnable() {

            @Override
            public void run() {
                try {
                    broker.start();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }

        }, 2L, TimeUnit.SECONDS);
        LifecycleHelper.initAndStart(connection);
    } finally {
        broker.destroy();
        LifecycleHelper.stopAndClose(connection);
        es.shutdownNow();
    }
}

From source file:org.libreoffice.impressremote.communication.CommunicationServiceWear.java

@Override
public void onDestroy() {
    Log.v(TAG, "onDestroy");
    if (null != googleApiClient) {
        notifyWearStop();//  w  w w  .  j av  a  2  s. c o  m
        final ScheduledExecutorService exec = Executors.newScheduledThreadPool(1);
        exec.schedule(new Runnable() {
            @Override
            public void run() {
                if (googleApiClient != null) {
                    if (googleApiClient.isConnected()) {
                        googleApiClient.disconnect();
                        Log.v(TAG, "GoogleApiClient disconnected");
                    }
                }
            }
        }, 2, TimeUnit.SECONDS);
    }
    super.onDestroy();
}

From source file:cherry.foundation.mail.SendMailBatchTest.java

@Test
public void testNormal() throws Exception {

    final File shutdownTrigger = new File("./shutdownTrigger.txt");
    shutdownTrigger.deleteOnExit();/* w w  w .  j  av  a2  s.  c  om*/
    Callable<Boolean> callable = new Callable<Boolean>() {
        @Override
        public Boolean call() {
            try (FileOutputStream os = new FileOutputStream(shutdownTrigger)) {
                return true;
            } catch (IOException ex) {
                return false;
            }
        }
    };

    ScheduledExecutorService service = Executors.newScheduledThreadPool(1);
    ScheduledFuture<Boolean> future = service.schedule(callable, 5L, TimeUnit.SECONDS);

    SendMailBatch batch = create(1000L, shutdownTrigger, false);
    ExitStatus status = batch.execute();

    assertEquals(ExitStatus.NORMAL, status);
    assertTrue(future.get().booleanValue());
    assertFalse(shutdownTrigger.exists());

    verify(bizDateTime, atLeastOnce()).now();
    verify(mailSendHandler, atLeastOnce()).listMessage((LocalDateTime) eq(null));
    verify(mailSendHandler, atLeastOnce()).sendMessage(eq(1L));
    verify(mailSendHandler, atLeastOnce()).sendMessage(eq(2L));
    verify(mailSendHandler, atLeastOnce()).sendMessage(eq(3L));
}

From source file:cherry.foundation.mail.SendMailBatchTest.java

@Test
public void testMailSendException() throws Exception {

    final File shutdownTrigger = new File("./shutdownTrigger.txt");
    shutdownTrigger.deleteOnExit();/*from  w  w w  .  ja v a2s  .  c  om*/
    Callable<Boolean> callable = new Callable<Boolean>() {
        @Override
        public Boolean call() {
            try (FileOutputStream os = new FileOutputStream(shutdownTrigger)) {
                return true;
            } catch (IOException ex) {
                return false;
            }
        }
    };

    ScheduledExecutorService service = Executors.newScheduledThreadPool(1);
    ScheduledFuture<Boolean> future = service.schedule(callable, 5L, TimeUnit.SECONDS);

    SendMailBatch batch = create(1000L, shutdownTrigger, true);
    ExitStatus status = batch.execute();

    assertEquals(ExitStatus.NORMAL, status);
    assertTrue(future.get().booleanValue());
    assertFalse(shutdownTrigger.exists());

    verify(bizDateTime, atLeastOnce()).now();
    verify(mailSendHandler, atLeastOnce()).listMessage((LocalDateTime) eq(null));
    verify(mailSendHandler, atLeastOnce()).sendMessage(eq(1L));
    verify(mailSendHandler, never()).sendMessage(eq(2L));
    verify(mailSendHandler, never()).sendMessage(eq(3L));
}