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:at.wada811.android.library.demos.concurrent.ExecutorActivity.java

/**
 * {@link ScheduledExecutorService#schedule(Runnable, long, TimeUnit)} ???
 * /*from   ww w. jav  a2  s. c  om*/
 * <p>
 * ???????????
 * </p>
 */
public void newSingleThreadScheduledExecutorDuringExecutionTest() {
    LogUtils.d();
    ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
    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:com.pepaproch.gtswsdl.client.RateLimitTest.java

private synchronized void addTask(AtomicInteger cc, ScheduledExecutorService schelduler, RateLimit rate,
        Instant[] end) {/*from  w w  w  .  java2  s. co m*/

    Callable<Integer> callable = (Callable<Integer>) () -> {

        return cc.get();
    };
    ListenableFutureTask request = new ListenableFutureTask(callable);

    schelduler.schedule(() -> {
        FutureTask<?> schelduledTask = request;
        if (!request.isCancelled() && !request.isDone()) {
            schelduledTask.run();
        }

    }, rate.consumeSlot(), TimeUnit.MILLISECONDS);

    request.addCallback(new ListenableFutureCallback<Integer>() {

        @Override
        public void onSuccess(Integer result) {
            cc.incrementAndGet();
            end[0] = Instant.now();
            System.out.println("FINISHEDLISTENBALE: " + result + end[0].toString());
        }

        @Override
        public void onFailure(Throwable ex) {
            System.out.println("FAILURE");
        }
    });

}

From source file:com.barchart.http.server.TestHttpServer.java

@Test(expected = HttpHostConnectException.class)
public void testKill() throws Exception {

    final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

    executor.schedule(new Runnable() {

        @Override/*from w w w .j a va 2 s  .  c  o m*/
        public void run() {
            server.kill();
        }

    }, 500, TimeUnit.MILLISECONDS);

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

    // Should throw exception
    client.execute(get);

}

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

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

From source file:com.barchart.netty.server.http.TestHttpServer.java

@Test(expected = HttpHostConnectException.class)
public void testKill() throws Exception {

    final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

    executor.schedule(new Runnable() {

        @Override// w ww .j  a v  a  2  s  .  c o  m
        public void run() {
            server.kill();
        }

    }, 500, TimeUnit.MILLISECONDS);

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

    // Should throw exception
    client.execute(get).getEntity();

}

From source file:com.smartx.bill.mepad.mestore.uimgloader.AbsListViewBaseActivity.java

protected void cancelDialog(boolean status) {
    if (status) {
        findViewById(id.me_topView).setVisibility(View.VISIBLE);
    } else if (!status) {
        findViewById(id.me_topView).setVisibility(View.INVISIBLE);
    }// w  w  w  .  j av  a 2s . com
    ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
    Runnable runner = new Runnable() {
        public void run() {
            dialog.dismiss();
        }
    };
    executor.schedule(runner, LayoutResourcesDatas.DELAY_TIME, TimeUnit.MILLISECONDS);
}

From source file:edu.umich.robot.HeadlessApplication.java

/**
 * <p>/*www  . ja  va2 s .c om*/
 * Start Soar, wait for timeout or Soar to stop.
 * 
 * @param controller
 *            Simulation controller initialized.
 * @throws InterruptedException
 *             Thrown on thread interrupt.
 */
private void run(Controller controller) throws InterruptedException {
    final CountDownLatch doneSignal = new CountDownLatch(1);

    Thread shutdownHook = new Thread() {
        @Override
        public void run() {
            logger.warn("Shutdown detected.");
            shutdown.set(true);
            doneSignal.countDown();
        }
    };

    Runtime.getRuntime().addShutdownHook(shutdownHook);

    try {
        controller.addListener(SoarStoppedEvent.class, new RobotEventListener() {
            public void onEvent(RobotEvent event) {
                logger.info("Soar stop detected.");
                doneSignal.countDown();
            }
        });

        ScheduledExecutorService schexec = MoreExecutors
                .getExitingScheduledExecutorService(new ScheduledThreadPoolExecutor(1));
        ScheduledFuture<?> task = null;
        if (seconds > 0) {
            task = schexec.schedule(new Runnable() {
                public void run() {
                    logger.info("Time up.");
                    doneSignal.countDown();
                }
            }, seconds, TimeUnit.SECONDS);
        }

        controller.startSoar(cycles);

        doneSignal.await();

        if (task != null)
            task.cancel(true);
        schexec.shutdown();
    } finally {
        if (!shutdown.get())
            Runtime.getRuntime().removeShutdownHook(shutdownHook);
    }
}

From source file:com.barchart.http.server.TestHttpServer.java

@Test
public void testShutdown() throws Exception {

    final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

    final AtomicBoolean pass = new AtomicBoolean(false);

    executor.schedule(new Runnable() {

        @Override//from  w  w w  . j av  a  2  s  . c  om
        public void run() {

            try {
                server.shutdown().sync();
            } catch (final InterruptedException e1) {
                e1.printStackTrace();
            }

            try {
                client.execute(new HttpGet("http://localhost:" + port + "/basic"));
            } catch (final HttpHostConnectException hhce) {
                pass.set(true);
            } catch (final Exception e) {
                e.printStackTrace();
            }

        }

    }, 1000, TimeUnit.MILLISECONDS);

    final HttpGet get = new HttpGet("http://localhost:" + port + "/client-disconnect");
    final HttpResponse response = client.execute(get);
    assertEquals(200, response.getStatusLine().getStatusCode());
    // assertTrue(pass.get());

}

From source file:org.springframework.scheduling.concurrent.ScheduledExecutorFactoryBean.java

/**
 * Register the specified {@link ScheduledExecutorTask ScheduledExecutorTasks}
 * on the given {@link ScheduledExecutorService}.
 * @param tasks the specified ScheduledExecutorTasks (never empty)
 * @param executor the ScheduledExecutorService to register the tasks on.
 *//*from  w  ww. ja  v  a  2s. c o  m*/
protected void registerTasks(ScheduledExecutorTask[] tasks, ScheduledExecutorService executor) {
    for (int i = 0; i < tasks.length; i++) {
        ScheduledExecutorTask task = tasks[i];
        Runnable runnable = getRunnableToSchedule(task);
        if (task.isOneTimeTask()) {
            executor.schedule(runnable, task.getDelay(), task.getTimeUnit());
        } else {
            if (task.isFixedRate()) {
                executor.scheduleAtFixedRate(runnable, task.getDelay(), task.getPeriod(), task.getTimeUnit());
            } else {
                executor.scheduleWithFixedDelay(runnable, task.getDelay(), task.getPeriod(),
                        task.getTimeUnit());
            }
        }
    }
}

From source file:com.magnet.mmx.util.AlertEventsManagerTest.java

public void testInterEmailTime() {
    setupMocks();/*from w  w w.  ja va  2  s . c o  m*/
    long testDurationMinutes = 5;
    MMXConfiguration.getConfiguration().setValue(MMXConfigKeys.ALERT_EMAIL_ENABLED, "true");
    MMXConfiguration.getConfiguration().setValue(MMXConfigKeys.ALERT_INTER_EMAIL_TIME_MINUTES, "1");
    ScheduledExecutorService executorService = Executors.newScheduledThreadPool(2);
    ScheduledFuture<?> future = executorService.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            AlertEventsManager.post(getRandomEvent());
        }
    }, 0L, 500, TimeUnit.MILLISECONDS);
    List<ScheduledFuture<?>> list = new ArrayList<ScheduledFuture<?>>();
    list.add(future);
    executorService.schedule(new StopTestTask(list), testDurationMinutes, TimeUnit.MINUTES);
    while (!future.isDone())
        ;
    LOGGER.trace("testInterEmailTime : average inter email time = {}", getAvg(elapsedTimes));
}