Java Code Examples for java.util.concurrent.ScheduledExecutorService#schedule()

The following examples show how to use java.util.concurrent.ScheduledExecutorService#schedule() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: neoscada   File: JdbcQuery.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public JdbcQuery ( final StorageDao jdbcStorageDao, final Filter filter, final ScheduledExecutorService executor, final List<JdbcQuery> openQueries ) throws SQLException, NotSupportedException
{
    openQueries.add ( this );
    this.openQueries = new WeakReference<List<JdbcQuery>> ( openQueries );
    this.jdbcStorageDao = jdbcStorageDao;
    this.resultSet = jdbcStorageDao.queryEvents ( filter );
    this.statement = this.resultSet.getStatement ();
    this.hasMore = this.resultSet.next ();
    this.future = executor.schedule ( new Callable<Boolean> () {
        @Override
        public Boolean call ()
        {
            logger.warn ( "Query '{}' was open for over an hour, or service is being shut down, and will now be closed automatically" );
            dispose ();
            return true;
        }
    }, 1, TimeUnit.HOURS );
}
 
Example 2
@Test
public void scheduleCallableCancelTest() {
  ScheduledExecutorService scheduler = makeScheduler(1);
  try {
    TestCallable tcDelay = new TestCallable(0);
    ScheduledFuture<Object> delayF = scheduler.schedule(tcDelay, 20, TimeUnit.MILLISECONDS);
    long delay = delayF.getDelay(TimeUnit.MILLISECONDS);
    boolean canceled = delayF.cancel(true);
    
    assertTrue(delay <= 20);
    if (canceled) {
      assertTrue(delayF.isCancelled());
    }
  } finally {
    scheduler.shutdownNow();
  }
}
 
Example 3
@Test(timeout = 2000)
public void emptyDefaultCompletable() throws Exception {
    ScheduledExecutorService exec = Executors.newScheduledThreadPool(1);
    try {
        DirectProcessor<Integer> sp = new DirectProcessor<>();
        
        Future<Integer> f = sp.toCompletableFuture(1);
        
        exec.schedule(() -> { sp.onComplete(); }, 500, TimeUnit.MILLISECONDS);
        
        Assert.assertEquals((Integer)1, f.get());
        
    } finally {
        exec.shutdown();
    }
}
 
Example 4
public static void main(String[] args) {
	logClassPathContent(); // We might not have a solution for this method when migrating to Java 9 - whats the best call?

	Monitor monitor = createMonitor();
	MonitorServer server = MonitorServer
			.create(monitor::currentStatistics)
			.start();

	ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
	scheduler.scheduleAtFixedRate(monitor::updateStatistics, 1, 1, TimeUnit.SECONDS);
	scheduler.schedule(() -> {
				scheduler.shutdown();
				server.shutdown();
			},
			10,
			TimeUnit.SECONDS);
}
 
Example 5
Source Project: more-lambdas-java   File: MoreFutures.java    License: Artistic License 2.0 6 votes vote down vote up
/**
 * @param task any exception throwing would cancel the task. user should swallow exceptions by self.
 * @param executor all task would be stopped after executor has been marked shutting down.
 * @return a future that can cancel the task.
 */
public static Future<?> scheduleWithDynamicDelay(@Nonnull ScheduledExecutorService executor,
        @Nullable Duration initDelay, @Nonnull Scheduled task) {
    checkNotNull(executor);
    checkNotNull(task);
    AtomicBoolean canceled = new AtomicBoolean(false);
    AbstractFuture<?> future = new AbstractFuture<Object>() {

        @Override
        public boolean cancel(boolean mayInterruptIfRunning) {
            canceled.set(true);
            return super.cancel(mayInterruptIfRunning);
        }
    };
    executor.schedule(new ScheduledTaskImpl(executor, task, canceled),
            initDelay == null ? 0 : initDelay.toMillis(), MILLISECONDS);
    return future;
}
 
Example 6
@Test(timeout = 2000)
public void emptyCompletable() throws Exception {
    ScheduledExecutorService exec = Executors.newScheduledThreadPool(1);
    try {
        DirectProcessor<Integer> sp = new DirectProcessor<>();
        
        Future<Integer> f = sp.toCompletableFuture();
        
        exec.schedule(() -> { sp.onComplete(); }, 500, TimeUnit.MILLISECONDS);

        try {
            Integer v = f.get();
            Assert.fail("Failed to throw ExecutionException and returned a value: " + v);
        } catch (ExecutionException ex) {
            if (!(ex.getCause() instanceof NoSuchElementException)) {
                throw ex;
            }
        }
        
    } finally {
        exec.shutdown();
    }
}
 
Example 7
Source Project: SoloPi   File: BackgroundExecutor.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Execute a runnable after the given delay.
 * @param runnable the task to execute
 * @param delay    the time from now to delay execution, in milliseconds
 * @return Future associated to the running task
 * @throws IllegalArgumentException if <code>delay</code> is strictly positive and the current
 *                                  executor does not support scheduling (if
 *                                  {@link #setExecutor(Executor)} has been called with such an
 *                                  executor)
 */
private static Future<?> directExecute(Runnable runnable, int delay) {
    Future<?> future = null;
    if (delay > 0) {
        /* no serial, but a delay: schedule the task */
        if (!(executor instanceof ScheduledExecutorService)) {
            throw new IllegalArgumentException("The executor set does not support scheduling");
        }
        ScheduledExecutorService scheduledExecutorService = (ScheduledExecutorService) executor;
        future = scheduledExecutorService.schedule(runnable, delay, TimeUnit.MILLISECONDS);
    } else {
        if (executor instanceof ExecutorService) {
            ExecutorService executorService = (ExecutorService) executor;
            future = executorService.submit(runnable);
        } else {
            /* non-cancellable task */
            executor.execute(runnable);
        }
    }
    return future;
}
 
Example 8
@Override
public final CompletableFuture<Endpoint> select(ClientRequestContext ctx,
                                                ScheduledExecutorService executor,
                                                long timeoutMillis) {
    Endpoint endpoint = selectNow(ctx);
    if (endpoint != null) {
        return UnmodifiableFuture.completedFuture(endpoint);
    }

    final ListeningFuture listeningFuture = new ListeningFuture(ctx, executor);
    endpointGroup.addListener(listeningFuture);

    // Try to select again because the EndpointGroup might have been updated
    // between selectNow() and addListener() above.
    endpoint = selectNow(ctx);
    if (endpoint != null) {
        endpointGroup.removeListener(listeningFuture);
        return UnmodifiableFuture.completedFuture(endpoint);
    }

    // Schedule the timeout task.
    final ScheduledFuture<?> timeoutFuture =
            executor.schedule(() -> listeningFuture.complete(null),
                              timeoutMillis, TimeUnit.MILLISECONDS);
    listeningFuture.timeoutFuture = timeoutFuture;

    // Cancel the timeout task if listeningFuture is done already.
    // This guards against the following race condition:
    // 1) (Current thread) Timeout task is scheduled.
    // 2) ( Other thread ) listeningFuture is completed, but the timeout task is not cancelled
    // 3) (Current thread) timeoutFuture is assigned to listeningFuture.timeoutFuture, but it's too late.
    if (listeningFuture.isDone()) {
        timeoutFuture.cancel(false);
    }

    return listeningFuture;
}
 
Example 9
public static void main(String[] args) {
    ScheduledExecutorService timer = Executors.newScheduledThreadPool(2);
    long delay = computeDelay();
    timer.schedule(new ThrowExceptionTask(timer), delay, TimeUnit.MILLISECONDS);
    timer.schedule(new NotThrowExceptionTask(timer), delay, TimeUnit.MILLISECONDS);
    System.out.println("主线程的功能执行完毕");
}
 
Example 10
@Test
public void testNewScheduledThreadPoolWithThreadFactory() throws Exception {
    final ScheduledExecutorService executorService = InstrumentedExecutors.newScheduledThreadPool(2, defaultThreadFactory, registry);
    executorService.schedule(new NoopRunnable(), 0, TimeUnit.SECONDS);

    final Field delegateField = InstrumentedScheduledExecutorService.class.getDeclaredField("delegate");
    delegateField.setAccessible(true);
    final ScheduledThreadPoolExecutor delegate = (ScheduledThreadPoolExecutor) delegateField.get(executorService);
    assertThat(delegate.getCorePoolSize()).isEqualTo(2);
    assertThat(delegate.getThreadFactory()).isSameAs(defaultThreadFactory);
    executorService.shutdown();
}
 
Example 11
Source Project: StubbornJava   File: FailsafeWebserver.java    License: MIT License 5 votes vote down vote up
public static void main(String[] args) {

        HttpHandler exceptionHandler =
                CustomHandlers.exception(CIRCUIT_BREAKER_HANDLER)
                              .addExceptionHandler(Throwable.class, FailsafeWebserver::serverError);

        SimpleServer server = SimpleServer.simpleServer(exceptionHandler);
        server.start();


        // Warm-up the circuit breaker it needs to hit at least max executions
        // Before it will reject anything. This will make that easier.
        for (int i = 0; i < 10; i++) {
            request("warmup", false, false);
        }
        ScheduledExecutorService schedExec = Executors.newScheduledThreadPool(1);

        // A simple request that should always succeed
        schedExec.scheduleAtFixedRate(() -> request("ping", false, false), 0, 500, TimeUnit.MILLISECONDS);

        // Send a batch of 15 bad requests to trigger the circuit breaker
        Runnable errors = () -> {
            log.info("Start: Executing bad requests!");
            for (int i = 0; i < 15; i++) {
                request("bad request", true, false);
            }
            log.info("End: Executing bad requests!");
        };
        schedExec.schedule(errors, 1, TimeUnit.SECONDS);

        // Send a batch of 15 requests that throw exceptions
        Runnable exceptions = () -> {
            log.info("Start: Executing requests that throw exceptions!");
            for (int i = 0; i < 15; i++) {
                request("exception request", false, true);
            }
            log.info("End: Executing requests that throw exceptions!");
        };
        schedExec.schedule(exceptions, 5, TimeUnit.SECONDS);
    }
 
Example 12
@Override
public ScheduledFuture<?> schedule(Runnable task, Date startTime) {
	ScheduledExecutorService executor = getScheduledExecutor();
	long initialDelay = startTime.getTime() - System.currentTimeMillis();
	try {
		return executor.schedule(errorHandlingTask(task, false), initialDelay, TimeUnit.MILLISECONDS);
	}
	catch (RejectedExecutionException ex) {
		throw new TaskRejectedException("Executor [" + executor + "] did not accept task: " + task, ex);
	}
}
 
Example 13
public static boolean isMaster(final HazelcastInstance hazelcastInstance, ScheduledExecutorService executor,
                               int delaySeconds) {
    if (hazelcastInstance == null || !isOldestMember(hazelcastInstance)) {
        return false;
    }
    try {
        Callable<Boolean> callable = () -> isOldestMember(hazelcastInstance);
        ScheduledFuture<Boolean> future = executor.schedule(callable, delaySeconds, TimeUnit.SECONDS);
        return future.get(TIMEOUT_SECONDS, TimeUnit.SECONDS);
    } catch (InterruptedException | ExecutionException | TimeoutException e) {
        throw new IllegalStateException(e);
    }
}
 
Example 14
Source Project: Chronicle-Network   File: UberHandler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * wait 2 seconds before closing the socket connection, this should allow time of the
 * termination event to be sent.
 */
private void closeSoon() {
    if (isClosing.compareAndSet(false, true)) {
        @NotNull final ScheduledExecutorService closer = newSingleThreadScheduledExecutor(new NamedThreadFactory("closer", true));
        closer.schedule(() -> {
            close();
            closer.shutdown();
        }, 2, SECONDS);
    }
}
 
Example 15
private void start(DataStoreService dataStoreService) {

        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(4);
        ThreadPoolExecutor checkDataNodeListChangeExecutor = new ThreadPoolExecutor(1, 2,
                0, TimeUnit.SECONDS, new SynchronousQueue<>());

        scheduler.schedule(new TimedSupervisorTask("CheckDataNodeListChange", scheduler,
                checkDataNodeListChangeExecutor, 500, TimeUnit.MILLISECONDS, 3,
                dataStoreService::pushNodeListChange), 1, TimeUnit.SECONDS);
    }
 
Example 16
Source Project: JDA   File: RestAction.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Schedules a call to {@link #queue(java.util.function.Consumer, java.util.function.Consumer)}
 * to be executed after the specified {@code delay}.
 * <br>This is an <b>asynchronous</b> operation that will return a
 * {@link java.util.concurrent.ScheduledFuture ScheduledFuture} representing the task.
 *
 * <p>The specified {@link java.util.concurrent.ScheduledExecutorService ScheduledExecutorService} is used for this operation.
 *
 * @param  delay
 *         The delay after which this computation should be executed, negative to execute immediately
 * @param  unit
 *         The {@link java.util.concurrent.TimeUnit TimeUnit} to convert the specified {@code delay}
 * @param  success
 *         The success {@link java.util.function.Consumer Consumer} that should be called
 *         once the {@link #queue(java.util.function.Consumer, java.util.function.Consumer)} operation completes successfully.
 * @param  failure
 *         The failure {@link java.util.function.Consumer Consumer} that should be called
 *         in case of an error of the {@link #queue(java.util.function.Consumer, java.util.function.Consumer)} operation.
 * @param  executor
 *         The Non-null {@link java.util.concurrent.ScheduledExecutorService ScheduledExecutorService} that should be used
 *         to schedule this operation
 *
 * @throws java.lang.IllegalArgumentException
 *         If the provided TimeUnit or ScheduledExecutorService is {@code null}
 *
 * @return {@link java.util.concurrent.ScheduledFuture ScheduledFuture}
 *         representing the delayed operation
 *
 * @see    net.dv8tion.jda.api.exceptions.ErrorHandler
 */
@Nonnull
default ScheduledFuture<?> queueAfter(long delay, @Nonnull TimeUnit unit, @Nullable Consumer<? super T> success, @Nullable Consumer<? super Throwable> failure, @Nullable ScheduledExecutorService executor)
{
    Checks.notNull(unit, "TimeUnit");
    if (executor == null)
        executor = getJDA().getRateLimitPool();

    final Consumer<? super Throwable> onFailure;
    if (isPassContext())
        onFailure = ContextException.here(failure == null ? getDefaultFailure() : failure);
    else
        onFailure = failure;

    Runnable task = new ContextRunnable<Void>(() -> queue(success, onFailure));
    return executor.schedule(task, delay, unit);
}
 
Example 17
Source Project: future   File: Promise.java    License: Apache License 2.0 4 votes vote down vote up
public WithinPromise(final InterruptHandler handler, final Duration timeout,
    final ScheduledExecutorService scheduler, final Throwable exception) {
  this.handler = handler;
  this.task = scheduler.schedule(this, timeout.toMillis(), TimeUnit.MILLISECONDS);
  this.exception = exception;
}
 
Example 18
private void delaySecondClick()
{
	final ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
	service.schedule(this::simLeftClick, randomDelay(90, 100), TimeUnit.MILLISECONDS);
	service.shutdown();
}
 
Example 19
Source Project: UltimateAndroid   File: IntentUtils.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * start screen capture after "delay" milliseconds, so the previous activity's
 * state recover to normal state, such as button click, list item click,wait
 * them to normal state so we can make a good screen capture
 *
 * @param context
 * @param intent
 * @param delay   time in milliseconds
 */
public static void startPreviewActivity(final Context context, final Intent intent, long delay) {
    final Handler mainThread = new Handler(Looper.getMainLooper());
    final Runnable postAction = new Runnable() {
        @Override
        public void run() {
            context.startActivity(intent);
        }
    };

    /** process screen capture on background thread */
    Runnable action = new Runnable() {
        @Override
        public void run() {
            /**
             * activity's root layout id, you can change the android.R.id.content to your root
             * layout id
             */
            final View contentView = ((Activity) context).findViewById(android.R.id.content);

            ByteArrayOutputStream baos = null;
            Bitmap bitmap = null;

            try {
                bitmap = Bitmap.createBitmap(contentView.getWidth(),
                        contentView.getHeight(), Bitmap.Config.ARGB_8888);
                contentView.draw(new Canvas(bitmap));

                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 70, baos);
                intent.putExtra(KEY_PREVIEW_IMAGE, baos.toByteArray());
            } finally {
                try {
                    /** no need to close, actually do nothing */
                    if (null != baos) baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (null != bitmap && !bitmap.isRecycled()) {
                    bitmap.recycle();
                    bitmap = null;
                }
            }
            mainThread.post(postAction);
        }
    };

    if (delay > 0) {
        ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor();
        worker.schedule(action, delay, TimeUnit.MILLISECONDS);
    } else {
        action.run();
    }
}
 
Example 20
Source Project: failsafe   File: Testing.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Returns a future that is completed with the {@code result} on the {@code executor}.
 */
public static CompletableFuture<Object> futureResult(ScheduledExecutorService executor, Object result) {
  CompletableFuture<Object> future = new CompletableFuture<>();
  executor.schedule(() -> future.complete(result), 0, TimeUnit.MILLISECONDS);
  return future;
}