java.util.concurrent.ScheduledFuture#cancel ( )源码实例Demo

下面列出了java.util.concurrent.ScheduledFuture#cancel ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

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());
}
 
源代码2 项目: j2objc   文件: ScheduledExecutorSubclassTest.java
/**
 * 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");
    }
}
 
源代码3 项目: openjdk-jdk9   文件: ScheduledExecutorTest.java
/**
 * 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);
    }
}
 
源代码4 项目: openhab-core   文件: UpnpIOServiceImpl.java
private void stopPollingForParticipant(UpnpIOParticipant participant) {
    if (pollingJobs.containsKey(participant)) {
        ScheduledFuture<?> pollingJob = pollingJobs.get(participant);
        if (pollingJob != null) {
            pollingJob.cancel(true);
        }
    }
}
 
源代码5 项目: smarthome   文件: MqttBrokerConnection.java
/**
 * 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);
    }
}
 
源代码6 项目: kubernetes-client   文件: RollingUpdater.java
/**
 * 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));
  }
}
 
源代码7 项目: atomix   文件: MulticastDiscoveryProvider.java
@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);
}
 
源代码8 项目: netbeans   文件: RequestProcessor180386Test.java
@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);
    }
}
 
源代码9 项目: smarthome   文件: DelayedBatchProcessing.java
/**
 * 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;
}
 
源代码10 项目: spring-boot-protocol   文件: RpcClient.java
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);
}
 
源代码11 项目: dremio-oss   文件: LocalSchedulerService.java
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);
  }
}
 
源代码12 项目: onos   文件: StatsPoller.java
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();
    }
}
 
源代码13 项目: x-pipe   文件: SentinelHelloCheckActionTest.java
@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();
}
 
源代码14 项目: spring-cloud-consul   文件: TtlScheduler.java
public void remove(String instanceId) {
	ScheduledFuture task = this.serviceHeartbeats.get(instanceId);
	if (task != null) {
		task.cancel(true);
	}
	this.serviceHeartbeats.remove(instanceId);
}
 
源代码15 项目: envelope   文件: Repetitions.java
/**
 * 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();
}
 
源代码16 项目: nebula   文件: IntensityGraphExample.java
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();

}
 
源代码17 项目: netty-4.1.22   文件: AbstractEpollChannel.java
@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();
    }
}
 
源代码18 项目: attic-stratos   文件: CloudControllerContext.java
private void stopTask(ScheduledFuture<?> task) {
    if (task != null) {
        task.cancel(true);
        log.info("Scheduled pod activation watcher task canceled");
    }
}
 
源代码19 项目: bazel   文件: BuildEventServiceModule.java
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();
  }
}
 
源代码20 项目: LuckPerms   文件: AbstractJavaScheduler.java
@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);
}