Java Code Examples for java.util.concurrent.ScheduledFuture#cancel()

The following examples show how to use java.util.concurrent.ScheduledFuture#cancel() . 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: ScheduledExecutorTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * scheduleWithFixedDelay executes runnable after given initial delay
 */
public void testSchedule5() throws Exception {
    final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
    try (PoolCleaner cleaner = cleaner(p)) {
        final long startTime = System.nanoTime();
        final CountDownLatch done = new CountDownLatch(1);
        Runnable task = new CheckedRunnable() {
            public void realRun() {
                done.countDown();
                assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
            }};
        ScheduledFuture f =
            p.scheduleWithFixedDelay(task, timeoutMillis(),
                                     LONG_DELAY_MS, MILLISECONDS);
        await(done);
        assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
        f.cancel(true);
    }
}
 
Example 2
Source File: ScheduledExecutorSubclassTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * purge removes cancelled tasks from the queue
 */
public void testPurge() throws InterruptedException {
    final ScheduledFuture[] tasks = new ScheduledFuture[5];
    final Runnable releaser = new Runnable() { public void run() {
        for (ScheduledFuture task : tasks)
            if (task != null) task.cancel(true); }};
    final CustomExecutor p = new CustomExecutor(1);
    try (PoolCleaner cleaner = cleaner(p, releaser)) {
        for (int i = 0; i < tasks.length; i++)
            tasks[i] = p.schedule(new SmallPossiblyInterruptedRunnable(),
                                  LONG_DELAY_MS, MILLISECONDS);
        int max = tasks.length;
        if (tasks[4].cancel(true)) --max;
        if (tasks[3].cancel(true)) --max;
        // There must eventually be an interference-free point at
        // which purge will not fail. (At worst, when queue is empty.)
        long startTime = System.nanoTime();
        do {
            p.purge();
            long count = p.getTaskCount();
            if (count == max)
                return;
        } while (millisElapsedSince(startTime) < LONG_DELAY_MS);
        fail("Purge failed to remove cancelled tasks");
    }
}
 
Example 3
Source File: ScheduledThreadPoolExecutorWithKeepAliveJUnitTest.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
public void testRepeatedExecution() throws InterruptedException {
  ex = new ScheduledThreadPoolExecutorWithKeepAlive(
      50, 1, TimeUnit.SECONDS, Executors.defaultThreadFactory());
  
  final AI counter = CFactory.createAI();
  Runnable run = new Runnable() {
    public void run() {
      counter.incrementAndGet();
    }
  };
  ScheduledFuture f = ex.scheduleAtFixedRate(run, 0, 1, TimeUnit.SECONDS);
  Thread.sleep(5000);
  f.cancel(true);
  assertTrue("Task was not executed repeatedly", counter.get() > 1);
  int oldValue = counter.get();
  Thread.sleep(5000);
  assertEquals("Task was not cancelled", oldValue, counter.get());
}
 
Example 4
Source File: MqttBrokerConnection.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * The connection process is limited by a timeout, realized with a {@link CompletableFuture}. Cancel that future
 * now, if it exists.
 */
protected void cancelTimeoutFuture() {
    final ScheduledFuture<?> timeoutFuture = this.timeoutFuture.getAndSet(null);
    if (timeoutFuture != null) {
        timeoutFuture.cancel(false);
    }
}
 
Example 5
Source File: Repetitions.java    From envelope with Apache License 2.0 5 votes vote down vote up
/**
 * Shutdown all currently scheduled tasks. Tasks are stopped by calling the {@code ScheduledFuture.cancel(true)}
 * method meaning that running tasks will be interrupted. After calling this method new tasks cannot be submitted and
 * a new {@code Repetitions} instance should be created with the {@see get(true)} method.
 */
public void shutdownTasks() {
  for (ScheduledFuture future : runningTasks) {
    future.cancel(true);
  }
  runningTasks.clear();
  executorService.shutdownNow();
}
 
Example 6
Source File: TtlScheduler.java    From spring-cloud-consul with Apache License 2.0 5 votes vote down vote up
public void remove(String instanceId) {
	ScheduledFuture task = this.serviceHeartbeats.get(instanceId);
	if (task != null) {
		task.cancel(true);
	}
	this.serviceHeartbeats.remove(instanceId);
}
 
Example 7
Source File: SentinelHelloCheckActionTest.java    From x-pipe with Apache License 2.0 5 votes vote down vote up
@Test
public void testDoScheduleTaskInterval() {
    action = spy(action);
    SentinelHelloCheckAction.SENTINEL_COLLECT_INFO_INTERVAL = 10;
    when(action.getIntervalMilli()).thenReturn(500);
    action.lastStartTime = System.currentTimeMillis() - 500;

    ScheduledFuture f = scheduled.scheduleWithFixedDelay(() -> action.doTask(), 0, 200, TimeUnit.MILLISECONDS);

    sleep(900);
    f.cancel(false);
    verify(action, times(2)).processSentinelHellos();
}
 
Example 8
Source File: StatsPoller.java    From onos with Apache License 2.0 5 votes vote down vote up
private void updatePollingTask(DeviceId deviceId) {
    deviceLocks.get(deviceId).lock();
    try {
        final ScheduledFuture<?> existingTask = statsPollingTasks.get(deviceId);
        final boolean shouldHaveTask = myScheme(deviceId)
                && deviceService.getDevice(deviceId) != null
                && deviceService.isAvailable(deviceId)
                && mastershipService.isLocalMaster(deviceId)
                && deviceService.getDevice(deviceId).is(PortStatisticsDiscovery.class);
        final boolean pollIntervalChanged = !Objects.equals(
                pollFrequencies.get(deviceId), statsPollInterval);

        if (existingTask != null && (!shouldHaveTask || pollIntervalChanged)) {
            existingTask.cancel(false);
            statsPollingTasks.remove(deviceId);
            pollFrequencies.remove(deviceId);
            log.info("Cancelled polling task for {}", deviceId);
        }

        if (shouldHaveTask) {
            if (statsPollingTasks.containsKey(deviceId)) {
                // There's already a task, with the same interval.
                return;
            }
            final int delay = new SecureRandom().nextInt(statsPollInterval);
            statsPollingTasks.put(deviceId, statsExecutor.scheduleAtFixedRate(
                    exceptionSafe(() -> updatePortStatistics(deviceId)),
                    delay, statsPollInterval, TimeUnit.SECONDS));
            pollFrequencies.put(deviceId, statsPollInterval);
            log.info("Started polling task for {} with interval {} seconds",
                     deviceId, statsPollInterval);
        }
    } finally {
        deviceLocks.get(deviceId).unlock();
    }
}
 
Example 9
Source File: LocalSchedulerService.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
private void basicCancel(boolean mayInterruptIfRunning) {
  if (cancelled.getAndSet(true)) {
    // Already cancelled
    return;
  }

  LOGGER.info(format("Cancelling task %s", task.toString()));
  ScheduledFuture<?> future = currentTask.getAndSet(null);
  if (future != null) {
    future.cancel(mayInterruptIfRunning);
  }
}
 
Example 10
Source File: RpcClient.java    From spring-boot-protocol with Apache License 2.0 5 votes vote down vote up
public void cancelScheduleReconnectTask(){
    ScheduledFuture scheduledFuture = this.reconnectScheduleFuture;
    if(scheduledFuture != null) {
        scheduledFuture.cancel(false);
    }
    BiConsumer<Long,RpcClient> reconnectSuccessHandler = this.reconnectTaskSuccessConsumer;
    if(reconnectSuccessHandler != null){
        reconnectSuccessHandler.accept(reconnectCount,this);
    }
    this.reconnectScheduleFuture = null;
    this.reconnectCount = 0;
    this.scheduleReconnectTaskIngFlag.set(false);
}
 
Example 11
Source File: DelayedBatchProcessing.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Return the so far accumulated objects, but do not deliver them to the target consumer anymore.
 *
 * @return A list of accumulated objects
 */
public List<TYPE> join() {
    ScheduledFuture<?> scheduledFuture = this.future;
    if (scheduledFuture != null && !scheduledFuture.isDone()) {
        scheduledFuture.cancel(false);
    }
    List<TYPE> lqueue = new ArrayList<>();
    synchronized (queue) {
        lqueue.addAll(queue);
        queue.clear();
    }
    return lqueue;
}
 
Example 12
Source File: RequestProcessor180386Test.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@RandomlyFails
public void testScheduleFixedRateWithShorterIntervalThanRunMethodTimeAreNotDelayed() throws Exception {
    final CountDownLatch latch = new CountDownLatch(10);
    final List<Long> intervals = new CopyOnWriteArrayList<Long>();
    class C implements Runnable {
        long start = Long.MIN_VALUE;

        @Override
        public void run() {
            long end = System.currentTimeMillis();
            if (start != Long.MIN_VALUE) {
                intervals.add(end - start);
            }
            try {
                Thread.sleep(500);
            } catch (InterruptedException ex) {
                
            }
            start = System.currentTimeMillis();
            latch.countDown();
        }
    }
    C c = new C();
    long initialDelay = 100;
    long period = 100;
    RequestProcessor rp = new RequestProcessor("testScheduleFixedRateWithShorterIntervalThanRunMethodTimeAreNotDelayed", 10, true);
    ScheduledFuture<?> f = rp.scheduleAtFixedRate(c, initialDelay, period, TimeUnit.MILLISECONDS);
    latch.await();
    f.cancel(true);
    rp.stop();
    int max = intervals.size();
    for (int i= 0; i < max; i++) {
        long iv = intervals.get(i);
        assertFalse ("Interval " + i + " should have been at least less than requested interval * 1.5 with fixed rate" + iv, iv > 150);
    }
}
 
Example 13
Source File: MulticastDiscoveryProvider.java    From atomix with Apache License 2.0 5 votes vote down vote up
@Override
public CompletableFuture<Void> leave(Node localNode) {
  if (nodes.remove(localNode.id()) != null) {
    post(new NodeDiscoveryEvent(NodeDiscoveryEvent.Type.LEAVE, localNode));
    bootstrap.getBroadcastService().removeListener(DISCOVERY_SUBJECT, broadcastListener);
    ScheduledFuture<?> broadcastFuture = this.broadcastFuture;
    if (broadcastFuture != null) {
      broadcastFuture.cancel(false);
    }
    LOGGER.info("Left");
  }
  return CompletableFuture.completedFuture(null);
}
 
Example 14
Source File: RollingUpdater.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
/**
 * Lets wait until there are enough Ready pods of the given RC
 */
private void waitUntilPodsAreReady(final T obj, final String namespace, final int requiredPodCount) {
  final CountDownLatch countDownLatch = new CountDownLatch(1);
  final AtomicInteger podCount = new AtomicInteger(0);

  final Runnable readyPodsPoller = () -> {
    PodList podList = listSelectedPods(obj);
    int count = 0;
    List<Pod> items = podList.getItems();
    for (Pod item : items) {
      for (PodCondition c : item.getStatus().getConditions()) {
        if (c.getType().equals("Ready") && c.getStatus().equals("True")) {
          count++;
        }
      }
    }
    podCount.set(count);
    if (count == requiredPodCount) {
      countDownLatch.countDown();
    }
  };

  ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
  ScheduledFuture poller = executor.scheduleWithFixedDelay(readyPodsPoller, 0, 1, TimeUnit.SECONDS);
  ScheduledFuture logger = executor.scheduleWithFixedDelay(() -> LOG.debug("Only {}/{} pod(s) ready for {}: {} in namespace: {} seconds so waiting...",
      podCount.get(), requiredPodCount, obj.getKind(), obj.getMetadata().getName(), namespace), 0, loggingIntervalMillis, TimeUnit.MILLISECONDS);
  try {
    countDownLatch.await(rollingTimeoutMillis, TimeUnit.MILLISECONDS);
    executor.shutdown();
  } catch (InterruptedException e) {
    Thread.currentThread().interrupt();
    poller.cancel(true);
    logger.cancel(true);
    executor.shutdown();
    LOG.warn("Only {}/{} pod(s) ready for {}: {} in namespace: {}  after waiting for {} seconds so giving up",
        podCount.get(), requiredPodCount, obj.getKind(), obj.getMetadata().getName(), namespace, TimeUnit.MILLISECONDS.toSeconds(rollingTimeoutMillis));
  }
}
 
Example 15
Source File: UpnpIOServiceImpl.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
private void stopPollingForParticipant(UpnpIOParticipant participant) {
    if (pollingJobs.containsKey(participant)) {
        ScheduledFuture<?> pollingJob = pollingJobs.get(participant);
        if (pollingJob != null) {
            pollingJob.cancel(true);
        }
    }
}
 
Example 16
Source File: AbstractEpollChannel.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
@Override
protected void doClose() throws Exception {
    active = false;
    // Even if we allow half closed sockets we should give up on reading. Otherwise we may allow a read attempt on a
    // socket which has not even been connected yet. This has been observed to block during unit tests.
    inputClosedSeenErrorOnRead = true;
    try {
        ChannelPromise promise = connectPromise;
        if (promise != null) {
            // Use tryFailure() instead of setFailure() to avoid the race against cancel().
            promise.tryFailure(DO_CLOSE_CLOSED_CHANNEL_EXCEPTION);
            connectPromise = null;
        }

        ScheduledFuture<?> future = connectTimeoutFuture;
        if (future != null) {
            future.cancel(false);
            connectTimeoutFuture = null;
        }

        if (isRegistered()) {
            // Need to check if we are on the EventLoop as doClose() may be triggered by the GlobalEventExecutor
            // if SO_LINGER is used.
            //
            // See https://github.com/netty/netty/issues/7159
            EventLoop loop = eventLoop();
            if (loop.inEventLoop()) {
                doDeregister();
            } else {
                loop.execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            doDeregister();
                        } catch (Throwable cause) {
                            pipeline().fireExceptionCaught(cause);
                        }
                    }
                });
            }
        }
    } finally {
        socket.close();
    }
}
 
Example 17
Source File: CloudControllerContext.java    From attic-stratos with Apache License 2.0 4 votes vote down vote up
private void stopTask(ScheduledFuture<?> task) {
    if (task != null) {
        task.cancel(true);
        log.info("Scheduled pod activation watcher task canceled");
    }
}
 
Example 18
Source File: BuildEventServiceModule.java    From bazel with Apache License 2.0 4 votes vote down vote up
private void waitForBuildEventTransportsToClose(
    Map<BuildEventTransport, ListenableFuture<Void>> transportFutures,
    boolean besUploadModeIsSynchronous)
    throws AbruptExitException {
  final ScheduledExecutorService executor =
      Executors.newSingleThreadScheduledExecutor(
          new ThreadFactoryBuilder().setNameFormat("bes-notify-ui-%d").build());
  ScheduledFuture<?> waitMessageFuture = null;

  try {
    // Notify the UI handler when a transport finished closing.
    transportFutures.forEach(
        (bepTransport, closeFuture) ->
            closeFuture.addListener(
                () -> {
                  reporter.post(new BuildEventTransportClosedEvent(bepTransport));
                },
                executor));

    try (AutoProfiler p = GoogleAutoProfilerUtils.logged("waiting for BES close")) {
      Uninterruptibles.getUninterruptibly(Futures.allAsList(transportFutures.values()));
    }
  } catch (ExecutionException e) {
    // Futures.withTimeout wraps the TimeoutException in an ExecutionException when the future
    // times out.
    if (isTimeoutException(e)) {
      throw createAbruptExitException(
          e,
          "The Build Event Protocol upload timed out.",
          ExitCode.TRANSIENT_BUILD_EVENT_SERVICE_UPLOAD_ERROR,
          BuildProgress.Code.BES_UPLOAD_TIMEOUT_ERROR);
    }

    Throwables.throwIfInstanceOf(e.getCause(), AbruptExitException.class);
    throw new RuntimeException(
        String.format(
            "Unexpected Exception '%s' when closing BEP transports, this is a bug.",
            e.getCause().getMessage()));
  } finally {
    if (besUploadModeIsSynchronous) {
      cancelAndResetPendingUploads();
    }
    if (waitMessageFuture != null) {
      waitMessageFuture.cancel(/* mayInterruptIfRunning= */ true);
    }
    executor.shutdown();
  }
}
 
Example 19
Source File: IntensityGraphExample.java    From nebula with Eclipse Public License 2.0 4 votes vote down vote up
public static void main(String[] args) {
	final Shell shell = new Shell();
	shell.setSize(300, 250);
	shell.open();

	// use LightweightSystem to create the bridge between SWT and draw2D
	final LightweightSystem lws = new LightweightSystem(shell);

	//Create Intensity Graph
	final IntensityGraphFigure intensityGraph = new IntensityGraphFigure();
	
	//Create Simulation Data
	final short[] simuData = new short[DataWidth * DataHeight * 2];
	final short[] data = new short[DataWidth * DataHeight];
	int seed = count++;
	for (int i = 0; i < DataHeight; i++) {
		for (int j = 0; j < DataWidth; j++) {
			int x = j - DataWidth;
			int y = i - DataHeight;
			int p = (int) Math.sqrt(x * x + y * y);
			simuData[i * DataWidth + j] = (short) (Math.sin(p * 2 * Math.PI
					/ DataWidth + seed * Math.PI / 100) * 100);
		}
	}

	//Configure
	intensityGraph.setMax(100);
	intensityGraph.setMin(-100);
	intensityGraph.setDataHeight(DataHeight);
	intensityGraph.setDataWidth(DataWidth);
	intensityGraph.setColorMap(new ColorMap(PredefinedColorMap.JET, true,true));
	intensityGraph.addROI("ROI 1",	new IROIListener() {
		
		@Override
		public void roiUpdated(int xIndex, int yIndex, int width, int height) {
			System.out.println("Region of Interest: (" + xIndex + ", " + yIndex 
					+", " + width +", " + height +")");
		}
	}, null);
	lws.setContents(intensityGraph);

	// Update the graph in another thread.
	ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
	ScheduledFuture<?> future = scheduler.scheduleAtFixedRate(
			new Runnable() {

				@Override
				public void run() {
					System.arraycopy(simuData, count % DataWidth, data, 0,
							DataWidth * DataHeight);

					Display.getDefault().asyncExec(new Runnable() {

						public void run() {
							count++;
							intensityGraph.setDataArray(simuData);
						}
					});
				}
			}, 100, 10, TimeUnit.MILLISECONDS);

	Display display = Display.getDefault();
	while (!shell.isDisposed()) {
		if (!display.readAndDispatch())
			display.sleep();
	}
	future.cancel(true);
	scheduler.shutdown();

}
 
Example 20
Source File: AbstractJavaScheduler.java    From LuckPerms with MIT License 4 votes vote down vote up
@Override
public SchedulerTask asyncLater(Runnable task, long delay, TimeUnit unit) {
    ScheduledFuture<?> future = this.scheduler.schedule(() -> this.schedulerWorkerPool.execute(task), delay, unit);
    return () -> future.cancel(false);
}