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.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));
}

From source file:org.jactr.tools.tracer.sinks.NetworkedSink.java

protected void scheduleFlush(long delay) {
    if (_scheduled)
        return;/* w  w w. j a va2 s .  c om*/
    _scheduled = true;

    ScheduledExecutorService executor = (ScheduledExecutorService) ExecutorServices
            .getExecutor(ExecutorServices.PERIODIC);
    try {
        executor.schedule(_autoFlush, delay, TimeUnit.MILLISECONDS);
    } catch (RejectedExecutionException ree) {
        if (LOGGER.isDebugEnabled())
            LOGGER.debug(String.format("Networked flush rejected, probably in the mids of shutdown"), ree);
    }
}

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

@Test
public void testInterrupt() throws Exception {

    final File shutdownTrigger = new File("./shutdownTrigger.txt");
    shutdownTrigger.deleteOnExit();/*from   w  w w  .  jav  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);
    final Thread currentThread = Thread.currentThread();
    ScheduledFuture<Boolean> interrupt = service.schedule(new Callable<Boolean>() {
        @Override
        public Boolean call() {
            currentThread.interrupt();
            return true;
        }
    }, 2L, TimeUnit.SECONDS);

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

    assertEquals(ExitStatus.NORMAL, status);
    assertTrue(future.get().booleanValue());
    assertTrue(interrupt.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:com.sbhstimetable.sbhs_timetable_android.backend.service.NotificationService.java

/**
 * Handle action Baz in the provided background thread with the provided
 * parameters./*w ww  .j a  v  a  2 s. co m*/
 */
private void handleNotificationUpdate() {
    NotificationManager m = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    if (!PreferenceManager.getDefaultSharedPreferences(this).getBoolean("notifications_enable", false)) {
        // only show a notification if it's configured
        m.cancel(NOTIFICATION_NEXT);
        return;
    }
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    builder.setSmallIcon(R.mipmap.ic_launcher);
    if (BelltimesJson.getInstance() == null)
        return;
    BelltimesJson.Bell next = BelltimesJson.getInstance().getNextBell();
    if (next == null) {
        // Show tomorrow. TODO
        m.cancel(NOTIFICATION_NEXT);
        return;
    }
    String title = next.getLabel();
    Integer[] b = next.getBell();
    b[0] = b[0] % 12;
    if (b[0] == 0)
        b[0] = 12;
    String subText = "at " + String.format("%02d:%02d", b);
    subText += (next.getBell()[0] >= 12 ? "pm" : "am");
    if (next.isPeriod() && TodayJson.getInstance() != null) {
        TodayJson.Period p = TodayJson.getInstance().getPeriod(next.getPeriodNumber());
        title = p.name() + " in " + p.room();
        subText += " with " + p.teacher();
    }
    builder.setContentTitle(title);
    builder.setContentText(subText);
    if (DateTimeHelper.milliSecondsUntilNextEvent() < 0) {
        Log.e("notificationService", "an event in the past? bailing out...");
        return;
    }
    Log.i("notificationService", "updating. time until next event: "
            + DateTimeHelper.formatToCountdown(DateTimeHelper.milliSecondsUntilNextEvent()));

    ScheduledExecutorService ses = new ScheduledThreadPoolExecutor(1);
    m.notify(NOTIFICATION_NEXT, builder.build());
    ses.schedule(new NotificationRunner(this), DateTimeHelper.milliSecondsUntilNextEvent(),
            TimeUnit.MILLISECONDS);
}

From source file:org.gss_project.gss.server.ejb.TransactionHelper.java

/**
 * Execute the supplied command until it completes, ignoring transaction
 * rollbacks. Try at least TRANSACTION_RETRIES times before giving up,
 * each time waiting a random amount of time, using an exponential
 * backoff scheme. See http://en.wikipedia.org/wiki/Exponential_backoff
 * for the basic idea./*from  w ww  .j a v a  2 s  .  c o m*/
 *
 * @param command the command to execute
 * @return the value returned by the command
 * @throws Exception any other exception thrown by the command
 */
public T tryExecute(final Callable<T> command) throws Exception {
    T returnValue = null;
    // Schedule a Future task to call the command after delay milliseconds.
    int delay = 0;
    ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
    for (int i = 0; i < TRANSACTION_RETRIES; i++) {
        final int retry = i;
        ScheduledFuture<T> future = executor.schedule(new Callable<T>() {

            @Override
            public T call() throws Exception {
                return command.call();
            }
        }, delay, TimeUnit.MILLISECONDS);

        try {
            returnValue = future.get();
            break;
        } catch (ExecutionException e) {
            Throwable cause = e.getCause();
            if (!(cause instanceof EJBTransactionRolledbackException) || retry == TRANSACTION_RETRIES - 1) {
                logger.info("Transaction retry #" + (i + 1) + " failed due to " + cause);
                executor.shutdownNow();
                if (cause instanceof Exception)
                    throw (Exception) cause;
                if (cause instanceof Error)
                    throw (Error) cause;
            }
            delay = MIN_TIMEOUT + (int) (MIN_TIMEOUT * Math.random() * (i + 1));
            String origCause = cause.getCause() == null ? cause.getClass().getName()
                    : cause.getCause().getClass().getName();
            logger.info(
                    "Transaction retry #" + (i + 1) + " scheduled in " + delay + " msec due to " + origCause);
        }

    }
    executor.shutdownNow();
    return returnValue;
}

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);//from w  ww . j  a v a 2s  .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.jorge.lolin1.ui.activities.DrawerLayoutFragmentActivity.java

@Override
public void onNavigationDrawerItemSelected(int position) {
    if (!navigatedItemsStack.isEmpty() && position == getLastSelectedNavDrawerIndex()) {
        //We don't want to perform an unnecessary Activity reload
        //noinspection UnnecessaryReturnStatement
        return;/*  w  w  w  . j  a  v a 2  s  . com*/
    } else {
        navigatedItemsStack.push(position);
    }

    Runnable task;
    switch (position) {
    case 0:
        task = new Runnable() {
            @Override
            public void run() {
                startActivity(new Intent(getApplicationContext(), NewsReaderActivity.class));
            }
        };
        break;
    case 1:
        task = new Runnable() {
            @Override
            public void run() {
                startActivity(new Intent(getApplicationContext(), JungleTimersActivity.class));
            }
        };
        break;
    case 2:
        task = new Runnable() {
            @Override
            public void run() {
                startActivity(new Intent(getApplicationContext(), ChampionListActivity.class));
            }
        };
        break;
    case 3:
        task = new Runnable() {
            @Override
            public void run() {
                startActivity(new Intent(getApplicationContext(), SurrReaderActivity.class));
            }
        };
        break;
    case 4:
        task = new Runnable() {
            @Override
            public void run() {
                startActivity(new Intent(getApplicationContext(), ChatOverviewActivity.class));
            }
        };
        break;
    default:
        Crashlytics.log(Log.ERROR, "debug", "Should never happen - Selected index - " + position);
        task = null;
    }
    if (task != null) {
        ScheduledExecutorService newActivityExecutor = Executors.newSingleThreadScheduledExecutor();
        newActivityExecutor.schedule(task, 0, TimeUnit.MILLISECONDS);
    }
}

From source file:com.barchart.http.handlers.TestCancellableRequestHandler.java

@Test
public void testCancellableRequest() throws Exception {

    final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

    final HttpGet get = new HttpGet("http://localhost:8888/client-disconnect");

    executor.schedule(new Runnable() {

        @Override/*from  w w  w  .j  a  va 2 s. c  o m*/
        public void run() {
            System.out.println("Aborting " + get);
            get.abort();
        }

    }, 250, TimeUnit.MILLISECONDS);

    try {
        System.out.println("Executing " + get);
        client.execute(get);
    } catch (final Exception e) {
    }

    CallableTest.waitFor(new Callable<Boolean>() {
        @Override
        public Boolean call() throws Exception {
            return clientDisconnect.lastFuture != null && clientDisconnect.lastFuture.isCancelled();
        }
    });

    assertNotNull(clientDisconnect.lastFuture);
    assertTrue(clientDisconnect.lastFuture.isCancelled());

}

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

/**
 * {@link Executors#newScheduledThreadPool(int)} ?
 * /*www  . j  a  v a  2 s.c  om*/
 * <p>
 * ???????????????????
 * </p>
 */
public void newScheduledThreadPoolTest() {
    LogUtils.d();
    ScheduledExecutorService executorService = Executors.newScheduledThreadPool(2);
    executorService.schedule(new ExecutorRunnable("A", 1), 1, TimeUnit.SECONDS);
    executorService.schedule(new ExecutorRunnable("B", 1), 1, TimeUnit.SECONDS);
    executorService.schedule(new ExecutorRunnable("C", 1), 1, TimeUnit.SECONDS);
    executorService.schedule(new ExecutorRunnable("D", 1), 1, TimeUnit.SECONDS);
}

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

/**
 * {@link ScheduledExecutorService#schedule(Runnable, long, TimeUnit)} ?????
 * /* w w  w.j a v  a 2 s  .com*/
 * <p>
 * ???????????
 * </p>
 */
public void newSingleThreadScheduledExecutorTest() {
    LogUtils.d();
    ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
    executorService.schedule(new ExecutorRunnable("A", 1), 8, TimeUnit.SECONDS);
    executorService.schedule(new ExecutorRunnable("B", 1), 4, TimeUnit.SECONDS);
    executorService.schedule(new ExecutorRunnable("C", 1), 0, TimeUnit.SECONDS);
    executorService.schedule(new ExecutorRunnable("D", 1), 12, TimeUnit.SECONDS);
}