当前位置: 首页>>代码示例>>Java>>正文


Java Cancellable类代码示例

本文整理汇总了Java中akka.actor.Cancellable的典型用法代码示例。如果您正苦于以下问题:Java Cancellable类的具体用法?Java Cancellable怎么用?Java Cancellable使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


Cancellable类属于akka.actor包,在下文中一共展示了Cancellable类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: scheduleWeeklyReport

import akka.actor.Cancellable; //导入依赖的package包/类
private void scheduleWeeklyReport() {
    FiniteDuration delay = FiniteDuration.create(secondsUntilNextMondayRun(), TimeUnit.SECONDS);
    Cancellable reportTask = tasks.remove("REPORT_SENDER");
    if (reportTask != null) {
        reportTask.cancel();
    }
    tasks.put("REPORT_SENDER", system.scheduler().scheduleOnce(delay, () -> {
        Logger.info("Running weekly email report");
        List<User> teachers = Ebean.find(User.class)
                .fetch("language")
                .where()
                .eq("roles.name", "TEACHER")
                .findList();
        teachers.forEach(t -> {
            try {
                composer.composeWeeklySummary(t);
            } catch (RuntimeException e) {
                Logger.error("Failed to send email for {}", t.getEmail());
            }
        });
        // Reschedule
        scheduleWeeklyReport();
    }, system.dispatcher()));
}
 
开发者ID:CSCfi,项目名称:exam,代码行数:25,代码来源:SystemInitializer.java

示例2: onSelectOwner

import akka.actor.Cancellable; //导入依赖的package包/类
private void onSelectOwner(final SelectOwner selectOwner) {
    LOG.debug("{}: onSelectOwner: {}", persistenceId(), selectOwner);

    String currentOwner = getCurrentOwner(selectOwner.getEntityPath());
    if (Strings.isNullOrEmpty(currentOwner)) {
        writeNewOwner(selectOwner.getEntityPath(), newOwner(currentOwner, selectOwner.getAllCandidates(),
                selectOwner.getOwnerSelectionStrategy()));

        Cancellable cancellable = entityToScheduledOwnershipTask.get(selectOwner.getEntityPath());
        if (cancellable != null) {
            if (!cancellable.isCancelled()) {
                cancellable.cancel();
            }
            entityToScheduledOwnershipTask.remove(selectOwner.getEntityPath());
        }
    }
}
 
开发者ID:hashsdn,项目名称:hashsdn-controller,代码行数:18,代码来源:EntityOwnershipShard.java

示例3: cancel

import akka.actor.Cancellable; //导入依赖的package包/类
void cancel(long executionId, Throwable throwable) {
    ActorRef child = getContext().getChild(String.valueOf(executionId));
    if (child != null) {
        if (!scheduledTerminations.containsKey(child)) {
            getContext().watch(child);
            child.tell(new Status.Failure(throwable), getSelf());

            // Give the top-level interpreter some time to finish. Otherwise, we will terminate it after a timeout.
            Cancellable scheduledTermination = getContext().system().scheduler().scheduleOnce(
                Duration.create(1, TimeUnit.MINUTES),
                child,
                PoisonPill.getInstance(),
                getContext().dispatcher(),
                getSelf()
            );
            scheduledTerminations.put(child, scheduledTermination);
        }
    } else {
        log.warning("Request to cancel unknown execution {} because of: {}", executionId, throwable);
    }
}
 
开发者ID:cloudkeeper-project,项目名称:cloudkeeper,代码行数:22,代码来源:MasterInterpreterActor.java

示例4: scheduleAtFixedRate

import akka.actor.Cancellable; //导入依赖的package包/类
@Override
@Nonnull
public ScheduledFuture<?> scheduleAtFixedRate(@Nonnull Runnable command, long initialDelay, long period, @Nonnull TimeUnit unit) {
	ScheduledFutureTask<Void> scheduledFutureTask = new ScheduledFutureTask<>(
		command,
		triggerTime(unit.toNanos(initialDelay)),
		unit.toNanos(period));

	Cancellable cancellable = actorSystem.scheduler().schedule(
		new FiniteDuration(initialDelay, unit),
		new FiniteDuration(period, unit),
		scheduledFutureTask,
		actorSystem.dispatcher());

	scheduledFutureTask.setCancellable(cancellable);

	return scheduledFutureTask;
}
 
开发者ID:axbaretto,项目名称:flink,代码行数:19,代码来源:ActorSystemScheduledExecutorAdapter.java

示例5: scheduleOnce

import akka.actor.Cancellable; //导入依赖的package包/类
@Override
public Cancellable scheduleOnce(final boolean exclusive, final String scheduledActionUuid, FiniteDuration initialDelay, final Runnable runnable) {
    if (log.isDebugEnabled()) {
        log.debug("Request " + (exclusive ? "EXCLUSIVE" : "STANDARD") + " " + scheduledActionUuid);
    }
    return getActorSystem().scheduler().scheduleOnce(initialDelay, new Runnable() {
        @Override
        public void run() {
            String transactionId = Utilities.getRandomID();
            dumpSystemStatus(
                    "ASYNC ACTION START for " + scheduledActionUuid + " [" + (exclusive ? "EXCLUSIVE" : "STANDARD") + "] and transaction " + transactionId);
            try {
                runnable.run();
            } catch (Exception e) {
                log.error("The job " + scheduledActionUuid + " raised an exception within the transaction " + transactionId, e);
            }
            dumpSystemStatus("ASYNC ACTION STOP for " + scheduledActionUuid + " and transaction " + transactionId);
        }
    }, getActorSystem().dispatcher());
}
 
开发者ID:theAgileFactory,项目名称:app-framework,代码行数:21,代码来源:SysAdminUtilsImpl.java

示例6: scheduleRecurring

import akka.actor.Cancellable; //导入依赖的package包/类
@Override
public Cancellable scheduleRecurring(final boolean exclusive, final String scheduledActionUuid, FiniteDuration initialDelay, FiniteDuration interval,
        final Runnable runnable, final boolean logInDebug) {
    if (log.isDebugEnabled()) {
        log.debug("Request " + (exclusive ? "EXCLUSIVE" : "STANDARD") + " " + scheduledActionUuid);
    }
    return getActorSystem().scheduler().schedule(initialDelay, interval, new Runnable() {
        @Override
        public void run() {
            String transactionId = Utilities.getRandomID();
            dumpSystemStatus(
                    "SCHEDULER START for " + scheduledActionUuid + " [" + (exclusive ? "EXCLUSIVE" : "STANDARD") + "] and transaction " + transactionId,
                    logInDebug);
            markAsStarted(transactionId, scheduledActionUuid);
            try {
                runnable.run();
            } catch (Exception e) {
                log.error("The job " + scheduledActionUuid + " raised an exception within the transaction " + transactionId, e);
            }
            markAsCompleted(transactionId, scheduledActionUuid);
            dumpSystemStatus("SCHEDULER STOP for " + scheduledActionUuid + " and transaction " + transactionId, logInDebug);
        }
    }, getActorSystem().dispatcher());
}
 
开发者ID:theAgileFactory,项目名称:app-framework,代码行数:25,代码来源:SysAdminUtilsImpl.java

示例7: StockActor

import akka.actor.Cancellable; //导入依赖的package包/类
public StockActor(String symbol, StockQuote stockQuote, boolean tick) {
    Optional<Cancellable> stockTick = tick ? Optional.of(scheduleTick()) : Optional.empty();

    receive(ReceiveBuilder
        .match(Stock.Latest.class, latest -> {
            // add a new stock price to the history and drop the oldest
            Double newPrice = stockQuote.newPrice(stockHistory.peekLast());
            stockHistory.add(newPrice);
            stockHistory.remove();
            // notify watchers
            watchers.forEach(watcher -> watcher.tell(new Stock.Update(symbol, newPrice), self()));
        })
        .match(Stock.Watch.class, watch -> {
            // reply with the stock history, and add the sender as a watcher
            final Double[] clone = stockHistory.toArray(new Double[]{});
            sender().tell(new Stock.History(symbol, clone), self());
            watchers.add(sender());
        })
        .match(Stock.Unwatch.class, unwatch -> {
            watchers.remove(sender());
            if (watchers.isEmpty()) {
                stockTick.ifPresent(Cancellable::cancel);
                context().stop(self());
            }
        }).build());
}
 
开发者ID:play2-maven-plugin,项目名称:play2-maven-test-projects,代码行数:27,代码来源:StockActor.java

示例8: addSubscription

import akka.actor.Cancellable; //导入依赖的package包/类
@Override
public Subscription addSubscription(SubscriptionRequestType request, String encoding) {
  log.debug("DdsProvider.addSubscription: requesterId=" + request.getRequesterId());

  // Populate a subscription object.
  Subscription subscription = new Subscription(request, encoding, configReader.getBaseURL());

  // Save the subscription.
  subscriptions.put(subscription.getId(), subscription);

  // Now we need to schedule the send of the initial set of matching
  // documents in a notification to this subscription.  We delay the
  // send so that the requester has time to return and store the
  // subscription identifier.
  SubscriptionEvent se = new SubscriptionEvent();
  se.setEvent(SubscriptionEvent.Event.New);
  se.setSubscription(subscription);
  Cancellable scheduleOnce = ddsActorController.scheduleNotification(se, 5);
  subscription.setAction(scheduleOnce);

  log.debug("DdsProvider.addSubscription: schedule notification delivery for " + subscription.getId());

  return subscription;
}
 
开发者ID:BandwidthOnDemand,项目名称:nsi-dds,代码行数:25,代码来源:DdsProvider.java

示例9: createReceive

import akka.actor.Cancellable; //导入依赖的package包/类
@Override
public Receive createReceive() {
    return receiveBuilder()
            .match(EnterGrid.class, msg -> {
                if (userMap.containsKey(msg.user.getUserId())) {
                    getSender().tell(false, getSelf());
                } else {
                    userMap.put(msg.user.getUserId(), msg.user);
                    getSender().tell(true, getSelf());
                }
            }).match(LeaveGrid.class, msg -> {
                if (userMap.containsKey(msg.userId)) {
                    userMap.remove(msg.userId);
                }
            }).match(GetPlayers.class, msg -> {
                Collection<IUser> values = userMap.values();
                List<IUser> list = new ArrayList<IUser>();
                list.addAll(values);
                getSender().tell(list, getSelf());
            })
            .match(ScheduleTask.class, msg -> {
                Scheduler scheduler = getContext().getSystem().scheduler();
                if (msg.isOnce()) {
                    Cancellable cancellable = scheduler.scheduleOnce(Duration.create(msg.getDelay(), TimeUnit.MILLISECONDS), msg.getTask(), getContext().getSystem().dispatcher());
                } else {
                    Cancellable schedule = scheduler.schedule(Duration.create(msg.getDelay(), TimeUnit.MILLISECONDS), Duration.create(msg.getInterval(), TimeUnit.MILLISECONDS), msg.getTask(), getContext().getSystem().dispatcher());
                }
            })
           .build();
}
 
开发者ID:zerosoft,项目名称:CodeBroker,代码行数:31,代码来源:GridActor.java

示例10: initiate

import akka.actor.Cancellable; //导入依赖的package包/类
@Override
public void initiate() {
    final AbstractLeader leader = (AbstractLeader) raftActor.getCurrentBehavior();
    AddServer addServer = getAddServerContext().getOperation();

    LOG.debug("{}: Initiating {}", raftContext.getId(), addServer);

    if (raftContext.getPeerInfo(addServer.getNewServerId()) != null) {
        operationComplete(getAddServerContext(), ServerChangeStatus.ALREADY_EXISTS);
        return;
    }

    VotingState votingState = addServer.isVotingMember() ? VotingState.VOTING_NOT_INITIALIZED :
            VotingState.NON_VOTING;
    raftContext.addToPeers(addServer.getNewServerId(), addServer.getNewServerAddress(), votingState);

    leader.addFollower(addServer.getNewServerId());

    if (votingState == VotingState.VOTING_NOT_INITIALIZED) {
        // schedule the install snapshot timeout timer
        Cancellable installSnapshotTimer = newInstallSnapshotTimer();
        if (leader.initiateCaptureSnapshot(addServer.getNewServerId())) {
            LOG.debug("{}: Initiating capture snapshot for new server {}", raftContext.getId(),
                    addServer.getNewServerId());

            currentOperationState = new InstallingSnapshot(getAddServerContext(), installSnapshotTimer);
        } else {
            LOG.debug("{}: Snapshot already in progress - waiting for completion", raftContext.getId());

            currentOperationState = new WaitingForPriorSnapshotComplete(getAddServerContext(),
                    installSnapshotTimer);
        }
    } else {
        LOG.debug("{}: New follower is non-voting - directly persisting new server configuration",
                raftContext.getId());

        persistNewServerConfiguration(getAddServerContext());
    }
}
 
开发者ID:hashsdn,项目名称:hashsdn-controller,代码行数:40,代码来源:RaftActorServerConfigurationSupport.java

示例11: scheduleOwnerSelection

import akka.actor.Cancellable; //导入依赖的package包/类
/**
 * Schedule a new owner selection job. Cancelling any outstanding job if it has not been cancelled.
 */
private void scheduleOwnerSelection(final YangInstanceIdentifier entityPath, final Collection<String> allCandidates,
                                   final EntityOwnerSelectionStrategy strategy) {
    cancelOwnerSelectionTask(entityPath);

    LOG.debug("{}: Scheduling owner selection after {} ms", persistenceId(), strategy.getSelectionDelayInMillis());

    final Cancellable lastScheduledTask = context().system().scheduler().scheduleOnce(
            FiniteDuration.apply(strategy.getSelectionDelayInMillis(), TimeUnit.MILLISECONDS), self(),
            new SelectOwner(entityPath, allCandidates, strategy), context().system().dispatcher(), self());

    entityToScheduledOwnershipTask.put(entityPath, lastScheduledTask);
}
 
开发者ID:hashsdn,项目名称:hashsdn-controller,代码行数:16,代码来源:EntityOwnershipShard.java

示例12: terminated

import akka.actor.Cancellable; //导入依赖的package包/类
void terminated(ActorRef child) {
    Cancellable scheduledTermination = scheduledTerminations.get(child);
    if (scheduledTermination != null) {
        // The child terminated in time, so we should cancel the scheduled termination.
        scheduledTermination.cancel();
    }
}
 
开发者ID:cloudkeeper-project,项目名称:cloudkeeper,代码行数:8,代码来源:MasterInterpreterActor.java

示例13: onJob

import akka.actor.Cancellable; //导入依赖的package包/类
private void onJob(final Master.Job job) {
    Cancellable abortLoop = getContext().system().scheduler().schedule(Duration.Zero(), Duration.create(60, TimeUnit.SECONDS),
            () -> {
                runCancelJob(job);
            }, getContext().system().dispatcher());
    ActorRef sender = getSender();
    ExecutorService pool = Executors.newFixedThreadPool(1);
    ExecutionContextExecutorService ctx = ExecutionContexts.fromExecutorService(pool);
    Future<Object> f = future(() -> runJob(job), ctx);
    f.onSuccess(new OnSuccess<Object>() {
        @Override
        public void onSuccess(Object result) throws Throwable {
            log.info("Notify Worker job status {}", result);
            sender.tell(result, getSelf());
            abortLoop.cancel();
        }
    }, ctx);
    f.onFailure(new OnFailure() {
        @Override
        public void onFailure(Throwable throwable) throws Throwable {
            log.error(throwable.toString());
            abortLoop.cancel();
            sender.tell(new Worker.WorkFailed(null), getSelf());
            unhandled(job);
        }
    }, ctx);
}
 
开发者ID:Abiy,项目名称:distGatling,代码行数:28,代码来源:JarExecutor.java

示例14: onJob

import akka.actor.Cancellable; //导入依赖的package包/类
private void onJob(final Master.Job job) {
    Cancellable abortLoop = getContext().system().scheduler().schedule(Duration.Zero(), Duration.create(60, TimeUnit.SECONDS),
            () -> {
                runCancelJob(job);
            }, getContext().system().dispatcher());
    ActorRef sender = getSender();
    ExecutorService pool = Executors.newFixedThreadPool(1);
    ExecutionContextExecutorService ctx = ExecutionContexts.fromExecutorService(pool);
    Future<Object> f = future(() -> runJob(job), ctx);
    f.onSuccess(new OnSuccess<Object>() {
        @Override
        public void onSuccess(Object result) throws Throwable {
            log.info("Notify Worker job status {}", result);
            sender.tell(result, getSelf());
            abortLoop.cancel();
        }
    }, ctx);
    f.onFailure(new OnFailure() {
        @Override
        public void onFailure(Throwable throwable) throws Throwable {
            log.error(throwable.toString());
            abortLoop.cancel();
            unhandled(job);
        }
    }, ctx);
    //getSender().tell(runJob(message));
}
 
开发者ID:Abiy,项目名称:distGatling,代码行数:28,代码来源:ScriptExecutor.java

示例15: schedule

import akka.actor.Cancellable; //导入依赖的package包/类
@Override
@Nonnull
public ScheduledFuture<?> schedule(@Nonnull Runnable command, long delay, @Nonnull TimeUnit unit) {
	ScheduledFutureTask<Void> scheduledFutureTask = new ScheduledFutureTask<>(command, unit.toNanos(delay), 0L);

	Cancellable cancellable = internalSchedule(scheduledFutureTask, delay, unit);

	scheduledFutureTask.setCancellable(cancellable);

	return scheduledFutureTask;
}
 
开发者ID:axbaretto,项目名称:flink,代码行数:12,代码来源:ActorSystemScheduledExecutorAdapter.java


注:本文中的akka.actor.Cancellable类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。