本文整理汇总了Java中java.util.concurrent.ScheduledFuture.cancel方法的典型用法代码示例。如果您正苦于以下问题:Java ScheduledFuture.cancel方法的具体用法?Java ScheduledFuture.cancel怎么用?Java ScheduledFuture.cancel使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.util.concurrent.ScheduledFuture
的用法示例。
在下文中一共展示了ScheduledFuture.cancel方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: onDeviceData
import java.util.concurrent.ScheduledFuture; //导入方法依赖的package包/类
private void onDeviceData(List<DeviceData> data) {
for (DeviceData dd : data) {
if (devices.add(dd.getName())) {
gateway.onDeviceConnect(dd.getName(), dd.getType());
}
if (!dd.getAttributes().isEmpty()) {
gateway.onDeviceAttributesUpdate(dd.getName(), dd.getAttributes());
}
if (!dd.getTelemetry().isEmpty()) {
gateway.onDeviceTelemetry(dd.getName(), dd.getTelemetry());
}
if (dd.getTimeout() != 0) {
ScheduledFuture<?> future = deviceKeepAliveTimers.get(dd.getName());
if (future != null) {
log.debug("Re-scheduling keep alive timer for device {} with timeout = {}", dd.getName(), dd.getTimeout());
future.cancel(true);
deviceKeepAliveTimers.remove(dd.getName());
scheduleDeviceKeepAliveTimer(dd);
} else {
log.debug("Scheduling keep alive timer for device {} with timeout = {}", dd.getName(), dd.getTimeout());
scheduleDeviceKeepAliveTimer(dd);
}
}
}
}
示例2: testSchedule4
import java.util.concurrent.ScheduledFuture; //导入方法依赖的package包/类
/**
* scheduleAtFixedRate executes runnable after given initial delay
*/
public void testSchedule4() throws InterruptedException {
final CustomExecutor p = new CustomExecutor(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.scheduleAtFixedRate(task, timeoutMillis(),
LONG_DELAY_MS, MILLISECONDS);
await(done);
assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
f.cancel(true);
}
}
示例3: scheduleWithFixedDelay
import java.util.concurrent.ScheduledFuture; //导入方法依赖的package包/类
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable task,
Date startTime, long delay) {
if (!enabled) {
logger.debug("skip : {}", task);
return null;
}
ScheduledFuture<?> future = instance.scheduleWithFixedDelay(task,
startTime, delay);
String runnableKey = findRunnableKey(task);
if (Boolean.FALSE.equals(skipMap.get(runnableKey))) {
future.cancel(true);
}
return future;
}
示例4: testPurge
import java.util.concurrent.ScheduledFuture; //导入方法依赖的package包/类
/**
* 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");
}
}
示例5: testFixedRateSequence
import java.util.concurrent.ScheduledFuture; //导入方法依赖的package包/类
/**
* 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");
}
}
示例6: registerService
import java.util.concurrent.ScheduledFuture; //导入方法依赖的package包/类
/**
* Registers a single service into consul.
*
* @param advertiseAddress The address the service is listening to.
* @param port The port that the service is listening on.
* @param serviceName The name of the service.
*/
private void registerService(final String advertiseAddress, final int port, final String serviceName) {
checkNotNull(Strings.emptyToNull(advertiseAddress), "advertiseAddress");
checkNotNull(Strings.emptyToNull(serviceName), "serviceName");
final String id = computeId(advertiseAddress, port, serviceName);
final NewService newService = new NewService();
newService.setId(id);
newService.setName(serviceName);
newService.setTags(tags);
newService.setAddress(advertiseAddress);
newService.setPort(port);
newService.setChecks(checks);
agentClient.agentServiceRegister(newService);
final ScheduledFuture future = scheduledExecutorService.scheduleAtFixedRate(
() -> heartbeat(id), heartbeatPeriod, heartbeatPeriod, heartbeatPeriodTimeUnit
);
final ScheduledFuture previous = servicePingers.put(id, future);
if (previous != null) {
previous.cancel(true);
}
}
示例7: close
import java.util.concurrent.ScheduledFuture; //导入方法依赖的package包/类
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");
}
示例8: testSchedule4
import java.util.concurrent.ScheduledFuture; //导入方法依赖的package包/类
/**
* scheduleAtFixedRate executes runnable after given initial delay
*/
public void testSchedule4() 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.scheduleAtFixedRate(task, timeoutMillis(),
LONG_DELAY_MS, MILLISECONDS);
await(done);
assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
f.cancel(true);
}
}
示例9: deregisterService
import java.util.concurrent.ScheduledFuture; //导入方法依赖的package包/类
/**
* Removes the service identified by the provided id from consul.
*
* @param id The id of the service.
*/
@VisibleForTesting
void deregisterService(final String id) {
agentClient.agentServiceDeregister(id);
final ScheduledFuture future = servicePingers.remove(id);
if (future != null) {
future.cancel(true);
}
}
示例10: testAppEnginePeriodicRunnable
import java.util.concurrent.ScheduledFuture; //导入方法依赖的package包/类
@Test
public void testAppEnginePeriodicRunnable() throws InterruptedException {
final Set<Long> threadIds = new HashSet<>();
final Semaphore semaphore = new Semaphore(0);
RevivingScheduledExecutor executor =
new RevivingScheduledExecutor(THREAD_FACTORY, "testAppEnginePeriodicRunnable", 0, 100);
ScheduledFuture<?> future =
executor.scheduleAtFixedRate(
new Runnable() {
@Override
public void run() {
threadIds.add(Thread.currentThread().getId());
semaphore.release();
}
},
0,
10,
TimeUnit.MILLISECONDS);
try {
Assert.assertTrue(semaphore.tryAcquire(50, 10, TimeUnit.SECONDS));
Assert.assertTrue(threadIds.size() > 1);
} finally {
future.cancel(true);
executor.shutdownNow();
}
}
示例11: removeSpawn
import java.util.concurrent.ScheduledFuture; //导入方法依赖的package包/类
/**
* Remove a registered spawn from the list, specified by the given spawn
* instance.
*
* @param spawnInst
* @return boolean removedSuccessfully
*/
@SuppressWarnings("rawtypes")
public boolean removeSpawn(AutoSpawnInstance spawnInst)
{
if (!isSpawnRegistered(spawnInst))
return false;
try
{
// Try to remove from the list of registered spawns if it exists.
_registeredSpawns.remove(spawnInst);
// Cancel the currently associated running scheduled task.
ScheduledFuture respawnTask = _runningSpawns.remove(spawnInst._objectId);
respawnTask.cancel(false);
if (Config.DEBUG)
_log.config("AutoSpawnHandler: Removed auto spawn for NPC ID "
+ spawnInst._npcId + " (Object ID = "
+ spawnInst._objectId + ").");
} catch (Exception e)
{
_log.warning("AutoSpawnHandler: Could not auto spawn for NPC ID "
+ spawnInst._npcId + " (Object ID = " + spawnInst._objectId
+ "): " + e);
return false;
}
return true;
}
示例12: setSpawnActive
import java.util.concurrent.ScheduledFuture; //导入方法依赖的package包/类
/**
* Sets the active state of the specified spawn.
*
* @param spawnInst
* @param isActive
*/
@SuppressWarnings("rawtypes")
public void setSpawnActive(AutoSpawnInstance spawnInst, boolean isActive)
{
if (spawnInst == null)
return;
int objectId = spawnInst._objectId;
if (isSpawnRegistered(objectId))
{
ScheduledFuture spawnTask = null;
if (isActive)
{
AutoSpawner rs = new AutoSpawner(objectId);
if (spawnInst._desDelay > 0)
spawnTask = ThreadPoolManager.getInstance().scheduleEffectAtFixedRate(rs,
spawnInst._initDelay, spawnInst._resDelay);
else
spawnTask = ThreadPoolManager.getInstance().scheduleEffect(rs, spawnInst._initDelay);
_runningSpawns.put(objectId, spawnTask);
} else
{
AutoDespawner rd = new AutoDespawner(objectId);
spawnTask = _runningSpawns.remove(objectId);
if (spawnTask != null)
spawnTask.cancel(false);
ThreadPoolManager.getInstance().scheduleEffect(rd, 0);
}
spawnInst.setSpawnActive(isActive);
}
}
示例13: registerPeriodic
import java.util.concurrent.ScheduledFuture; //导入方法依赖的package包/类
/**
* Registers a periodic task.
* @param task the task to execute.
* @param delay the delay to first execution.
* @param period the period between executions.
* @param timeout the time to interruption.
* @param unit the time unit.
*/
private static void registerPeriodic(Runnable task, long delay, long period, long timeout, TimeUnit unit) {
final ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1);
final ScheduledFuture<?> handler =
scheduler.scheduleAtFixedRate(task, delay, period, unit);
if (timeout > 0) {
Runnable interrupt = () -> handler.cancel(true);
scheduler.schedule(interrupt, timeout, TimeUnit.SECONDS);
}
}
示例14: stopHeartbeatTimer
import java.util.concurrent.ScheduledFuture; //导入方法依赖的package包/类
private void stopHeartbeatTimer() {
try {
ScheduledFuture<?> timer = heatbeatTimer;
if (timer != null && ! timer.isCancelled()) {
timer.cancel(true);
}
} catch (Throwable t) {
logger.warn(t.getMessage(), t);
} finally {
heatbeatTimer =null;
}
}
示例15: testScheduleFixedRateWithShorterIntervalThanRunMethodTimeAreNotDelayed
import java.util.concurrent.ScheduledFuture; //导入方法依赖的package包/类
@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);
}
}