Example usage for java.util.concurrent ScheduledFuture cancel

List of usage examples for java.util.concurrent ScheduledFuture cancel

Introduction

In this page you can find the example usage for java.util.concurrent ScheduledFuture cancel.

Prototype

boolean cancel(boolean mayInterruptIfRunning);

Source Link

Document

Attempts to cancel execution of this task.

Usage

From source file:org.eclipse.smarthome.binding.astro.handler.AstroThingHandler.java

/**
 * Stops all jobs for this thing.//from www . j  a  va 2 s . c  o  m
 */
private void stopJobs() {
    logger.debug("Stopping scheduled jobs for thing {}", getThing().getUID());
    monitor.lock();
    try {
        if (scheduledExecutor != null) {
            if (dailyJob != null) {
                scheduledExecutor.remove(dailyJob);
            }
            dailyJob = null;
        }
        for (ScheduledFuture<?> future : scheduledFutures) {
            if (!future.isDone()) {
                future.cancel(true);
            }
        }
        scheduledFutures.clear();
    } catch (Exception ex) {
        logger.error("{}", ex.getMessage(), ex);
    } finally {
        monitor.unlock();
    }
}

From source file:org.springframework.statemachine.state.AbstractState.java

/**
 * Cancel existing state actions and clear list.
 */// www  . j  av  a2s .  c  o  m
protected void cancelStateActions() {
    for (ScheduledFuture<?> future : cancellableActions) {
        future.cancel(true);
    }
    cancellableActions.clear();
}

From source file:org.eclipse.smarthome.binding.mqtt.generic.internal.generic.ChannelState.java

private void receivedOrTimeout() {
    final ScheduledFuture<?> scheduledFuture = this.scheduledFuture;
    if (scheduledFuture != null) { // Cancel timeout
        scheduledFuture.cancel(false);
        this.scheduledFuture = null;
    }// w  w  w. ja va2s.c  o  m
    future.complete(null);
}

From source file:org.eclipse.smarthome.binding.mqtt.generic.internal.generic.ChannelState.java

private @Nullable Void subscribeFail(Throwable e) {
    final ScheduledFuture<?> scheduledFuture = this.scheduledFuture;
    if (scheduledFuture != null) { // Cancel timeout
        scheduledFuture.cancel(false);
        this.scheduledFuture = null;
    }//  w  w w.j  a  v a 2 s .c om
    future.completeExceptionally(e);
    return null;
}

From source file:com.janrain.backplane.server.MessageProcessor.java

@Override
public void takeLeadership(CuratorFramework curatorFramework) throws Exception {
    setLeader(true);/*from w  ww . j a  v a 2 s .  c om*/
    logger.info("[" + BackplaneSystemProps.getMachineName() + "] v1 leader elected for message processing");

    ScheduledFuture<?> cleanupTask = scheduledExecutor.scheduleAtFixedRate(cleanupRunnable, 2, 2,
            TimeUnit.HOURS);
    insertMessages();
    cleanupTask.cancel(false);

    logger.info("[" + BackplaneSystemProps.getMachineName() + "] v1 leader ended message processing");
}

From source file:com.janrain.backplane2.server.V2MessageProcessor.java

@Override
public void takeLeadership(CuratorFramework curatorFramework) throws Exception {
    setLeader(true);//from  w  w  w  .jav a  2  s . c  o  m
    logger.info("[" + BackplaneSystemProps.getMachineName() + "] v2 leader elected for message processing");

    ScheduledFuture<?> cleanupTask = scheduledExecutor.scheduleAtFixedRate(cleanupRunnable, 1, 2,
            TimeUnit.HOURS);
    insertMessages();
    cleanupTask.cancel(false);

    logger.info("[" + BackplaneSystemProps.getMachineName() + "] v2 leader ended message processing");
}

From source file:org.hawkular.alerter.elasticsearch.ElasticsearchAlerter.java

private synchronized void update() {
    final Set<TriggerKey> existingKeys = queryFutures.keySet();
    final Set<TriggerKey> activeKeys = activeTriggers.keySet();

    Set<TriggerKey> newKeys = new HashSet<>();
    Set<TriggerKey> canceledKeys = new HashSet<>();

    Set<TriggerKey> updatedKeys = new HashSet<>(activeKeys);
    updatedKeys.retainAll(activeKeys);//w w  w . j a va2 s . c om

    activeKeys.stream().filter(key -> !existingKeys.contains(key)).forEach(key -> newKeys.add(key));
    existingKeys.stream().filter(key -> !activeKeys.contains(key)).forEach(key -> canceledKeys.add(key));

    log.debugf("newKeys %s", newKeys);
    log.debugf("updatedKeys %s", updatedKeys);
    log.debugf("canceledKeys %s", canceledKeys);

    canceledKeys.stream().forEach(key -> {
        ScheduledFuture canceled = queryFutures.remove(key);
        if (canceled != null) {
            canceled.cancel(false);
        }
    });
    updatedKeys.stream().forEach(key -> {
        ScheduledFuture updated = queryFutures.remove(key);
        if (updated != null) {
            updated.cancel(false);
        }
    });

    if (scheduledExecutor == null) {
        scheduledExecutor = new ScheduledThreadPoolExecutor(THREAD_POOL_SIZE);
    }

    newKeys.addAll(updatedKeys);

    for (TriggerKey key : newKeys) {
        Trigger t = activeTriggers.get(key);
        String interval = t.getContext().get(INTERVAL) == null ? INTERVAL_DEFAULT
                : t.getContext().get(INTERVAL);
        queryFutures.put(key,
                scheduledExecutor.scheduleAtFixedRate(new ElasticsearchQuery(t, defaultProperties, alerts), 0L,
                        getIntervalValue(interval), getIntervalUnit(interval)));

    }
}

From source file:com.netflix.genie.web.tasks.job.JobMonitoringCoordinatorUnitTests.java

/**
 * Make sure when a {@link com.netflix.genie.core.events.JobFinishedEvent} is sent the monitor is cancelled.
 *
 * @throws GenieException on error//from w w  w. j a va2  s  .c o m
 */
@Test
@SuppressWarnings("unchecked")
public void canStopJobMonitor() throws GenieException {
    final String job1Id = UUID.randomUUID().toString();
    final JobExecution.Builder builder = new JobExecution.Builder(UUID.randomUUID().toString())
            .withProcessId(2818).withCheckDelay(DELAY).withMemory(1024).withTimeout(this.tomorrow);
    builder.withId(job1Id);
    final JobExecution job1 = builder.build();
    final String job2Id = UUID.randomUUID().toString();
    builder.withId(job2Id);
    final JobExecution job2 = builder.build();

    final JobStartedEvent startedEvent1 = new JobStartedEvent(job1, this);
    final JobFinishedEvent finishedEvent1 = new JobFinishedEvent(job1Id, JobFinishedReason.PROCESS_COMPLETED,
            "something", this);
    final JobStartedEvent startedEvent2 = new JobStartedEvent(job2, this);
    final JobFinishedEvent finishedEvent2 = new JobFinishedEvent(job2Id, JobFinishedReason.KILLED, "something",
            this);

    final ScheduledFuture future1 = Mockito.mock(ScheduledFuture.class);
    Mockito.when(future1.cancel(true)).thenReturn(true);
    final ScheduledFuture future2 = Mockito.mock(ScheduledFuture.class);
    Mockito.when(future2.cancel(true)).thenReturn(false);

    Mockito.when(this.scheduler.scheduleWithFixedDelay(Mockito.any(JobMonitor.class), Mockito.eq(DELAY)))
            .thenReturn(future1, future2);

    Assert.assertThat(this.coordinator.getNumActiveJobs(), Matchers.is(0));
    Assert.assertThat(this.coordinator.getUsedMemory(), Matchers.is(0));
    coordinator.init(job1Id);
    coordinator.schedule(job1Id, null, null, null, null, 1024);
    this.coordinator.onJobStarted(startedEvent1);
    Assert.assertThat(this.coordinator.getNumActiveJobs(), Matchers.is(1));
    Assert.assertThat(this.coordinator.getUsedMemory(), Matchers.is(1024));
    coordinator.init(job2Id);
    coordinator.schedule(job2Id, null, null, null, null, 1024);
    this.coordinator.onJobStarted(startedEvent2);
    Assert.assertThat(this.coordinator.getNumActiveJobs(), Matchers.is(2));
    Assert.assertThat(this.coordinator.getUsedMemory(), Matchers.is(2048));

    Mockito.verify(this.scheduler, Mockito.times(2)).scheduleWithFixedDelay(Mockito.any(JobMonitor.class),
            Mockito.eq(DELAY));

    Assert.assertThat(this.coordinator.getNumActiveJobs(), Matchers.is(2));
    Assert.assertThat(this.coordinator.getUsedMemory(), Matchers.is(2048));
    this.coordinator.onJobFinished(finishedEvent1);
    Assert.assertThat(this.coordinator.getNumActiveJobs(), Matchers.is(1));
    Assert.assertThat(this.coordinator.getUsedMemory(), Matchers.is(1024));
    this.coordinator.onJobFinished(finishedEvent2);
    Assert.assertThat(this.coordinator.getNumActiveJobs(), Matchers.is(0));
    Assert.assertThat(this.coordinator.getUsedMemory(), Matchers.is(0));
    this.coordinator.onJobFinished(finishedEvent1);
    Assert.assertThat(this.coordinator.getNumActiveJobs(), Matchers.is(0));
    Assert.assertThat(this.coordinator.getUsedMemory(), Matchers.is(0));

    Mockito.verify(future1, Mockito.times(1)).cancel(true);
    Mockito.verify(future2, Mockito.times(1)).cancel(true);
    Mockito.verify(this.unableToCancel, Mockito.times(1)).increment();
}

From source file:org.openhab.binding.lifx.internal.LifxLightDiscovery.java

@Override
protected void stopBackgroundDiscovery() {
    logger.debug("Stopping LIFX device background discovery");

    ScheduledFuture<?> localDiscoveryJob = discoveryJob;
    if (localDiscoveryJob != null && !localDiscoveryJob.isCancelled()) {
        localDiscoveryJob.cancel(true);
        discoveryJob = null;//from  w  w w.ja  v a2 s  . co m
    }

    ScheduledFuture<?> localNetworkJob = networkJob;
    if (localNetworkJob != null && !localNetworkJob.isCancelled()) {
        localNetworkJob.cancel(true);
        networkJob = null;
    }
}

From source file:com.vmware.thinapp.manualmode.util.JobMonitorService.java

/**
 * Stop monitoring the VM with the given moid.
 *
 * @param vmMoid the moid of the VM to stop monitoring.
 *//*from w  w  w. j av a  2 s.  c o m*/
public void stopMonitoring(JobMonitorTicket ticket) {
    if (ticket != null) {
        ScheduledFuture<?> taskHandle = perfTasks.remove(ticket);
        if (taskHandle != null) {
            log.debug("Stopping performance monitoring for VM {}.", ticket.getId());
            taskHandle.cancel(true);
        }
    }
}