java.util.concurrent.ScheduledFuture Java Examples
The following examples show how to use
java.util.concurrent.ScheduledFuture.
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 File: ScheduledExecutorSubclassTest.java From j2objc with Apache License 2.0 | 6 votes |
/** * scheduleAtFixedRate executes series of tasks at given rate. * Eventually, it must hold that: * cycles - 1 <= elapsedMillis/delay < cycles */ public void testFixedRateSequence() throws InterruptedException { final CustomExecutor p = new CustomExecutor(1); try (PoolCleaner cleaner = cleaner(p)) { for (int delay = 1; delay <= LONG_DELAY_MS; delay *= 3) { final long startTime = System.nanoTime(); final int cycles = 8; final CountDownLatch done = new CountDownLatch(cycles); final Runnable task = new CheckedRunnable() { public void realRun() { done.countDown(); }}; final ScheduledFuture periodicTask = p.scheduleAtFixedRate(task, 0, delay, MILLISECONDS); final int totalDelayMillis = (cycles - 1) * delay; await(done, totalDelayMillis + LONG_DELAY_MS); periodicTask.cancel(true); final long elapsedMillis = millisElapsedSince(startTime); assertTrue(elapsedMillis >= totalDelayMillis); if (elapsedMillis <= cycles * delay) return; // else retry with longer delay } fail("unexpected execution rate"); } }
Example #2
Source File: ProxyTaskScheduler.java From lemon with Apache License 2.0 | 6 votes |
public ScheduledFuture<?> schedule(Runnable task, Trigger trigger) { if (!enabled) { logger.debug("skip : {}", task); return null; } ScheduledFuture<?> future = instance.schedule(task, trigger); String runnableKey = findRunnableKey(task); if (Boolean.FALSE.equals(skipMap.get(runnableKey))) { future.cancel(true); } return future; }
Example #3
Source File: SimpleBrokerMessageHandlerTests.java From spring-analysis-note with MIT License | 6 votes |
@SuppressWarnings("unchecked") @Test public void startAndStopWithHeartbeatValue() { ScheduledFuture future = mock(ScheduledFuture.class); given(this.taskScheduler.scheduleWithFixedDelay(any(Runnable.class), eq(15000L))).willReturn(future); this.messageHandler.setTaskScheduler(this.taskScheduler); this.messageHandler.setHeartbeatValue(new long[] {15000, 16000}); this.messageHandler.start(); verify(this.taskScheduler).scheduleWithFixedDelay(any(Runnable.class), eq(15000L)); verifyNoMoreInteractions(this.taskScheduler, future); this.messageHandler.stop(); verify(future).cancel(true); verifyNoMoreInteractions(future); }
Example #4
Source File: LocalCacheService.java From component-runtime with Apache License 2.0 | 6 votes |
@Override public <T> T computeIfAbsent(final Class<T> expectedClass, final String key, final Predicate<Element> toRemove, final long timeoutMs, final Supplier<T> value) { final Integer maxSize = this.getConfigValue(CacheConfiguration::getDefaultMaxSize, -1); if (maxSize > 0 && this.cache.size() >= maxSize) { this.clean(); // clean before add one element. if (this.cache.size() >= maxSize) { synchronized (this.cache) { while (this.cache.size() >= maxSize) { final String keyToRemove = this.cache.keySet().iterator().next(); this.cache.remove(keyToRemove); } } } } final ScheduledFuture<?> task = timeoutMs > 0 ? this.evictionTask(key, timeoutMs) : null; final long endOfValidity = this.calcEndOfValidity(timeoutMs); final ElementImpl element = this.addToMap(key, () -> new ElementImpl(value, toRemove, endOfValidity, task, this.timer)); return element.getValue(expectedClass); }
Example #5
Source File: FutureUtils.java From flink with Apache License 2.0 | 6 votes |
/** * Times the given future out after the timeout. * * @param future to time out * @param timeout after which the given future is timed out * @param timeUnit time unit of the timeout * @param timeoutFailExecutor executor that will complete the future exceptionally after the timeout is reached * @param <T> type of the given future * @return The timeout enriched future */ public static <T> CompletableFuture<T> orTimeout( CompletableFuture<T> future, long timeout, TimeUnit timeUnit, Executor timeoutFailExecutor) { if (!future.isDone()) { final ScheduledFuture<?> timeoutFuture = Delayer.delay( () -> timeoutFailExecutor.execute(new Timeout(future)), timeout, timeUnit); future.whenComplete((T value, Throwable throwable) -> { if (!timeoutFuture.isDone()) { timeoutFuture.cancel(false); } }); } return future; }
Example #6
Source File: MockScheduledExecutor.java From floodlight_with_topoguard with Apache License 2.0 | 5 votes |
@Override public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) { if (ses == null) ses = Executors.newScheduledThreadPool(1); try { return ses.scheduleAtFixedRate(command, initialDelay, period, unit); } catch (Exception e) { return new MockFuture<Object>(new ExecutionException(e)); } }
Example #7
Source File: FailoverHotSwapDataSourceCreator.java From cobarclient with Apache License 2.0 | 5 votes |
public void destroy() throws Exception { for (Map.Entry<ScheduledFuture<?>, ScheduledExecutorService> e : schedulerFutures .entrySet()) { ScheduledFuture<?> future = e.getKey(); ScheduledExecutorService scheduler = e.getValue(); future.cancel(true); shutdownExecutor(scheduler); } for (ExecutorService executor : jobExecutorRegistry) { shutdownExecutor(executor); } }
Example #8
Source File: PendingCheckpoint.java From flink with Apache License 2.0 | 5 votes |
private void cancelCanceller() { try { final ScheduledFuture<?> canceller = this.cancellerHandle; if (canceller != null) { canceller.cancel(false); } } catch (Exception e) { // this code should not throw exceptions LOG.warn("Error while cancelling checkpoint timeout task", e); } }
Example #9
Source File: PollingUsbSerialScanner.java From openhab-core with Eclipse Public License 2.0 | 5 votes |
/** * Stops repeatedly scanning for newly added and removed USB devices. This can be restarted using * {@link #startBackgroundScanning()}. */ @Override public synchronized void stopBackgroundScanning() { logger.debug("Stopping USB-Serial background discovery"); ScheduledFuture<?> currentBackgroundScanningJob = backgroundScanningJob; if (currentBackgroundScanningJob != null && !currentBackgroundScanningJob.isCancelled()) { if (currentBackgroundScanningJob.cancel(true)) { backgroundScanningJob = null; logger.debug("Stopped USB-serial background discovery"); } } }
Example #10
Source File: AsyncService.java From live-chat-engine with Apache License 2.0 | 5 votes |
/** * Good for simple cases * <pre> * task --- delay --- task * </pre> */ public void tryScheduleWithFixedDelay(String commandName, CallableVoid command, long initialDelayMs, long delayMs){ logScheduleWithFixedDelay(commandName, delayMs); ScheduledFuture<?> future = scheduledService.scheduleWithFixedDelay(()->{ try { command.call(); }catch(Throwable t){ log.error("can't scheduleWithFixedDelay", t); } }, initialDelayMs, delayMs, TimeUnit.MILLISECONDS); fireScheduleEvent(future); }
Example #11
Source File: SingularityHealthchecker.java From Singularity with Apache License 2.0 | 5 votes |
private ScheduledFuture<?> enqueueHealthcheckWithDelay( final SingularityTask task, long delaySeconds, final boolean inStartup ) { LOG.trace( "Enqueuing a healthcheck for task {} with delay {}", task.getTaskId(), DurationFormatUtils.formatDurationHMS(TimeUnit.SECONDS.toMillis(delaySeconds)) ); return executorService.schedule( new Runnable() { @Override public void run() { try { asyncHealthcheck(task); } catch (Throwable t) { LOG.error("Uncaught throwable in async healthcheck", t); exceptionNotifier.notify( String.format( "Uncaught throwable in async healthcheck (%s)", t.getMessage() ), t, ImmutableMap.of("taskId", task.getTaskId().toString()) ); reEnqueueOrAbort(task, inStartup); } } }, delaySeconds, TimeUnit.SECONDS ); }
Example #12
Source File: TestQuery.java From morphia with Apache License 2.0 | 5 votes |
@Test public void testTailableCursors() { getMapper().map(CappedPic.class); final Datastore ds = getDs(); ds.ensureCaps(); final Query<CappedPic> query = ds.find(CappedPic.class); final List<CappedPic> found = new ArrayList<>(); final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1); assertEquals(0, query.count()); ScheduledFuture<?> scheduledFuture = executorService.scheduleAtFixedRate( () -> ds.save(new CappedPic()), 0, 100, TimeUnit.MILLISECONDS); Awaitility .await() .atMost(10, TimeUnit.SECONDS) .until(() -> getDs().find(CappedPic.class).count() > 0); final Iterator<CappedPic> tail = query.iterator(new FindOptions() .cursorType(CursorType.Tailable)); Awaitility .await() .pollDelay(500, TimeUnit.MILLISECONDS) .atMost(10, TimeUnit.SECONDS) .until(() -> { if (tail.hasNext()) { found.add(tail.next()); } return found.size() >= 10; }); executorService.shutdownNow(); Assert.assertTrue(found.size() >= 10); Assert.assertTrue(query.count() >= 10); }
Example #13
Source File: AkkaRpcServiceTest.java From flink with Apache License 2.0 | 5 votes |
/** * Tests that the RPC service's scheduled executor service can execute runnable with a fixed * delay. */ @Test(timeout = 60000) public void testScheduledExecutorServiceWithFixedDelaySchedule() throws Exception { ScheduledExecutor scheduledExecutor = akkaRpcService.getScheduledExecutor(); final int tries = 4; final long delay = 10L; final CountDownLatch countDownLatch = new CountDownLatch(tries); long currentTime = System.nanoTime(); ScheduledFuture<?> future = scheduledExecutor.scheduleWithFixedDelay( countDownLatch::countDown, delay, delay, TimeUnit.MILLISECONDS); assertTrue(!future.isDone()); countDownLatch.await(); // the future should not complete since we have a periodic task assertTrue(!future.isDone()); long finalTime = System.nanoTime() - currentTime; // the processing should have taken at least delay times the number of count downs. assertTrue(finalTime >= tries * delay); future.cancel(true); }
Example #14
Source File: FileCacheDirectoriesTest.java From Flink-CEPplus with Apache License 2.0 | 5 votes |
@Override public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) { if (command instanceof FileCache.DeleteProcess) { assertNull("Multiple delete process registered", lastDeleteProcess); lastDeleteProcess = (FileCache.DeleteProcess) command; lastDelayMillis = unit.toMillis(delay); return super.schedule(() -> {}, delay, unit); } else { return super.schedule(command, delay, unit); } }
Example #15
Source File: ReschedulingRunnable.java From audit4j-core with Apache License 2.0 | 5 votes |
/** * {@inheritDoc} * * @see java.util.concurrent.Future#get(long, java.util.concurrent.TimeUnit) * */ @Override public Object get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { ScheduledFuture<?> curr; synchronized (this.triggerContextMonitor) { curr = this.currentFuture; } return curr.get(timeout, unit); }
Example #16
Source File: TaskCenter.java From util4j with Apache License 2.0 | 5 votes |
public void close() { System.out.println("TaskCenter closing"); this.monitoring.cancel(true); // 停止所有定时任务 for (ScheduledFuture<?> sf : this.scheduledFutureList) { if (!sf.isCancelled() || !sf.isDone()) { sf.cancel(true); } } this.scheduledFutureList.clear(); Iterator<Timer> iter = this.timers.values().iterator(); while (iter.hasNext()) { Timer timer = iter.next(); timer.cancel(); } this.timers.clear(); // 关闭滑动窗 this.slidingWindow.stop(); // 关闭线程池 this.mainExecutor.shutdown(); this.scheduledExecutor.shutdown(); System.out.println("TaskCenter closed"); }
Example #17
Source File: ActorTimerExecuterService.java From actor4j-core with Apache License 2.0 | 5 votes |
@Override public ScheduledFuture<?> scheduleOnce(final Supplier<ActorMessage<?>> supplier, final ActorGroup group, long delay, TimeUnit unit) { return timerExecuterService.schedule(new Runnable() { @Override public void run() { ActorMessage<?> message = supplier.get(); for (UUID id : group) { message.dest = id; system.send(message); } } }, delay, unit); }
Example #18
Source File: LazyTraceThreadPoolTaskScheduler.java From elasticactors with Apache License 2.0 | 5 votes |
@Override public ScheduledFuture<?> scheduleAtFixedRate( Runnable task, Instant startTime, Duration period) { return this.delegate.scheduleAtFixedRate(TraceRunnable.wrap(task), startTime, period); }
Example #19
Source File: FirebaseApp.java From firebase-admin-java with Apache License 2.0 | 5 votes |
<T> ScheduledFuture<T> schedule(Callable<T> command, long delayMillis) { checkNotNull(command); try { return ensureScheduledExecutorService().schedule(command, delayMillis, TimeUnit.MILLISECONDS); } catch (Exception e) { // This may fail if the underlying ThreadFactory does not support long-lived threads. throw new UnsupportedOperationException("Scheduled tasks not supported", e); } }
Example #20
Source File: ControlledScheduledExecutorService.java From tez with Apache License 2.0 | 5 votes |
@Override public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) { ScheduledFutureTask<Void> task = new ScheduledFutureTask<>(command, null, toTimestamp(initialDelay, unit), unit.toMillis(delay)); schedule(task); return task; }
Example #21
Source File: ChannelState.java From smarthome with Eclipse Public License 2.0 | 5 votes |
private void receivedOrTimeout() { final ScheduledFuture<?> scheduledFuture = this.scheduledFuture; if (scheduledFuture != null) { // Cancel timeout scheduledFuture.cancel(false); this.scheduledFuture = null; } future.complete(null); }
Example #22
Source File: SearchIndex.java From haven-platform with Apache License 2.0 | 5 votes |
@Override public void close() throws Exception { ScheduledFuture<?> future = this.future; if(future != null) { future.cancel(true); } }
Example #23
Source File: FakeClock.java From grpc-nebula-java with Apache License 2.0 | 5 votes |
@Override public ScheduledFuture<?> schedule(Runnable cmd, long delay, TimeUnit unit) { ScheduledTask task = new ScheduledTask(currentTimeNanos + unit.toNanos(delay), cmd); if (delay > 0) { scheduledTasks.add(task); } else { dueTasks.add(task); } return task; }
Example #24
Source File: MockHealthStatisticsGenerator.java From attic-stratos with Apache License 2.0 | 5 votes |
/** * Schedule statistics updater tasks for the given service/cartridge type. * * @param serviceName service name/cartridge type */ public void scheduleStatisticsUpdaterTasks(String serviceName) { synchronized (MockHealthStatisticsGenerator.class) { if (!statisticsUpdaterTasksScheduled(serviceName)) { List<MockHealthStatisticsPattern> statisticsPatterns = MockIaasConfig.getInstance(). getMockHealthStatisticsConfig().getStatisticsPatterns(); Map<String, ScheduledFuture> taskList = serviceNameToTaskListMap.get(serviceName); if (taskList == null) { taskList = new ConcurrentHashMap<String, ScheduledFuture>(); serviceNameToTaskListMap.put(serviceName, taskList); } for (MockHealthStatisticsPattern statisticsPattern : statisticsPatterns) { if (statisticsPattern.getCartridgeType().equals(serviceName) && (statisticsPattern.getSampleDuration() > 0)) { MockHealthStatisticsUpdater runnable = new MockHealthStatisticsUpdater(statisticsPattern); ScheduledFuture<?> task = scheduledExecutorService.scheduleAtFixedRate(runnable, 0, statisticsPattern.getSampleDuration(), TimeUnit.SECONDS); taskList.put(statisticsPattern.getFactor().toString(), task); } } if (log.isInfoEnabled()) { log.info(String.format("Mock statistics updaters scheduled: [service-name] %s", serviceName)); } } } }
Example #25
Source File: ReschedulingExecutor.java From GitToolBox with Apache License 2.0 | 5 votes |
public Future<?> schedule(String id, Runnable task, long delay, TimeUnit timeUnit) { if (active.get()) { ScheduledFuture<?> newFuture = executor.schedule(task, delay, timeUnit); log.debug("Scheduled ", id, ": ", task); Optional.ofNullable(tasks.put(id, newFuture)).ifPresent(oldFuture -> { log.debug("Cancelling ", id, " interrupt=", mayInterrupt, ": ", oldFuture); oldFuture.cancel(mayInterrupt); log.debug("Cancelled ", id, " interrupt=", mayInterrupt, ": ", oldFuture); }); return newFuture; } else { log.debug("Schedule ", id, " while inactive: ", task); return Futures.immediateCancelledFuture(); } }
Example #26
Source File: SubscriptionManagerTest.java From fiware-cepheus with GNU General Public License v2.0 | 5 votes |
@Test public void testUnsubscribeOnEventTypeRemoval() { // Mock the task scheduler and capture the runnable ArgumentCaptor<Runnable> runnableArg = ArgumentCaptor.forClass(Runnable.class); when(taskScheduler.scheduleWithFixedDelay(runnableArg.capture(), anyLong())).thenReturn(Mockito.mock(ScheduledFuture.class)); // Mock the response to the subsribeContext ArgumentCaptor<SuccessCallback> successArg = ArgumentCaptor.forClass(SuccessCallback.class); ListenableFuture<SubscribeContextResponse> responseFuture = Mockito.mock(ListenableFuture.class); doNothing().when(responseFuture).addCallback(successArg.capture(), any()); // Return the mocked future on subscription when(ngsiClient.subscribeContext(any(), any(), any())).thenReturn(responseFuture); Configuration configuration = getBasicConf(); subscriptionManager.setConfiguration(configuration); // Execute scheduled runnable runnableArg.getValue().run(); // Return the SubscribeContextResponse callSuccessCallback(successArg); // Mock future for unsubscribeContext ListenableFuture<UnsubscribeContextResponse> responseFuture2 = Mockito.mock(ListenableFuture.class); doNothing().when(responseFuture2).addCallback(successArg.capture(), any()); when(ngsiClient.unsubscribeContext(eq("http://iotAgent"), eq(null), eq("12345678"))).thenReturn(responseFuture2); // Set a configuration without the eventType Configuration emptyConfiguration = new Configuration(); emptyConfiguration.setEventTypeIns(Collections.emptyList()); subscriptionManager.setConfiguration(emptyConfiguration); // Check that unsubsribe is called when a later configuration removed the event type Assert.notNull(successArg.getValue()); }
Example #27
Source File: DefaultSchedulingManager.java From dhis2-core with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Override public void scheduleJob( JobConfiguration jobConfiguration ) { if ( ifJobInSystemStop( jobConfiguration.getUid() ) ) { JobInstance jobInstance = new DefaultJobInstance( this, messageService, leaderManager ); if ( jobConfiguration.getUid() != null && !futures.containsKey( jobConfiguration.getUid() ) ) { log.info( String.format( "Scheduling job: %s", jobConfiguration ) ); ScheduledFuture<?> future = null; if ( jobConfiguration.getJobType().isCronSchedulingType() ) { future = jobScheduler.schedule( () -> jobInstance.execute( jobConfiguration ), new CronTrigger( jobConfiguration.getCronExpression() ) ); } else if ( jobConfiguration.getJobType().isFixedDelaySchedulingType() ) { future = jobScheduler.scheduleWithFixedDelay( () -> jobInstance.execute( jobConfiguration ), Instant.now().plusSeconds( DEFAULT_INITIAL_DELAY_S ), Duration.of( jobConfiguration.getDelay(), ChronoUnit.SECONDS ) ); } futures.put( jobConfiguration.getUid(), future ); log.info( String.format( "Scheduled job: %s", jobConfiguration ) ); } } }
Example #28
Source File: LdapTimeoutTest.java From openjdk-8-source with GNU General Public License v2.0 | 5 votes |
ScheduledFuture killSwitch() { final Thread current = Thread.currentThread(); return LdapTimeoutTest.pool.schedule(new Callable<Void>() { public Void call() throws Exception { System.err.println("Fail: killSwitch()"); current.interrupt(); return null; } }, 5000, TimeUnit.MILLISECONDS); }
Example #29
Source File: ZigBeeNetworkManager.java From com.zsmartsystems.zigbee with Eclipse Public License 1.0 | 5 votes |
/** * Stops the current execution of a task and schedules a runnable task for execution again. * This uses a fixed size scheduler to limit thread execution. * * @param futureTask the {@link ScheduledFuture} for the current scheduled task * @param runnableTask the {@link Runnable} to execute * @param delay the delay in milliseconds before the task will be executed * @return the {@link ScheduledFuture} for the scheduled task */ public ScheduledFuture<?> rescheduleTask(ScheduledFuture<?> futureTask, Runnable runnableTask, long delay) { futureTask.cancel(false); if (networkState != ZigBeeNetworkState.ONLINE) { logger.debug("ZigBeeNetworkManager rescheduleTask: not scheduling task while {}", networkState); return null; } return executorService.schedule(runnableTask, delay, TimeUnit.MILLISECONDS); }
Example #30
Source File: ScheduledExecutorSubclassTest.java From j2objc with Apache License 2.0 | 5 votes |
/** * shutdownNow returns a list containing tasks that were not run, * and those tasks are drained from the queue */ public void testShutdownNow_delayedTasks() throws InterruptedException { final CustomExecutor p = new CustomExecutor(1); List<ScheduledFuture> tasks = new ArrayList<>(); for (int i = 0; i < 3; i++) { Runnable r = new NoOpRunnable(); tasks.add(p.schedule(r, 9, SECONDS)); tasks.add(p.scheduleAtFixedRate(r, 9, 9, SECONDS)); tasks.add(p.scheduleWithFixedDelay(r, 9, 9, SECONDS)); } if (testImplementationDetails) assertEquals(new HashSet(tasks), new HashSet(p.getQueue())); final List<Runnable> queuedTasks; try { queuedTasks = p.shutdownNow(); } catch (SecurityException ok) { return; // Allowed in case test doesn't have privs } assertTrue(p.isShutdown()); assertTrue(p.getQueue().isEmpty()); if (testImplementationDetails) assertEquals(new HashSet(tasks), new HashSet(queuedTasks)); assertEquals(tasks.size(), queuedTasks.size()); for (ScheduledFuture task : tasks) { assertFalse(((CustomTask)task).ran); assertFalse(task.isDone()); assertFalse(task.isCancelled()); } assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS)); assertTrue(p.isTerminated()); }