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())); }
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()); } } }
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); } }
@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; }
@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()); }
@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()); }
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()); }
@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; }
@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(); }
@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()); } }
/** * 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); }
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(); } }
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); }
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)); }
@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; }
@Override @Nonnull public <V> ScheduledFuture<V> schedule(@Nonnull Callable<V> callable, long delay, @Nonnull TimeUnit unit) { ScheduledFutureTask<V> scheduledFutureTask = new ScheduledFutureTask<>(callable, unit.toNanos(delay), 0L); Cancellable cancellable = internalSchedule(scheduledFutureTask, delay, unit); scheduledFutureTask.setCancellable(cancellable); return scheduledFutureTask; }
@Override @Nonnull public ScheduledFuture<?> scheduleWithFixedDelay(@Nonnull Runnable command, long initialDelay, long delay, @Nonnull TimeUnit unit) { ScheduledFutureTask<Void> scheduledFutureTask = new ScheduledFutureTask<>( command, triggerTime(unit.toNanos(initialDelay)), unit.toNanos(-delay)); Cancellable cancellable = internalSchedule(scheduledFutureTask, initialDelay, unit); scheduledFutureTask.setCancellable(cancellable); return scheduledFutureTask; }
@Override public Cancellable schedule(long initialDelay, long interval, String actorName, Object message) { ActorRef actor = getActor(actorName); if (actor == null) { return null; } FiniteDuration initial = new FiniteDuration(initialDelay, TimeUnit.MILLISECONDS); FiniteDuration gap = new FiniteDuration(interval, TimeUnit.MILLISECONDS); Scheduler scheduler = actorSystem.scheduler(); return scheduler.schedule(initial, gap, actor, message, actorSystem.dispatcher(), ActorRef.noSender()); }
@Override public Cancellable runOnce(long initialDelay, String actorName, Object message) { ActorRef actor = getActor(actorName); if (actor == null) { return null; } FiniteDuration initial = new FiniteDuration(initialDelay, TimeUnit.MILLISECONDS); Scheduler scheduler = actorSystem.scheduler(); return scheduler.scheduleOnce(initial, actor, message, actorSystem.dispatcher(), ActorRef.noSender()); }
public void cancel() { log.info("***** START cancel JobsServiceImpl ****"); for (Cancellable scheduler : schedulers) { if (scheduler != null) { scheduler.cancel(); log.info("***** Scheduler was not null and is cancelled ****"); } } log.info("***** END cancel JobsServiceImpl ****"); }
default Source<JsonNode, ?> getJsonSource() { final DateTimeFormatter df = DateTimeFormatter.ISO_INSTANT; final Source<String, Cancellable> tickSource = Source.tick(Duration.Zero(), Duration.create(100, MILLISECONDS), "TICK"); return tickSource.map((tick) -> { ObjectNode result = Json.newObject(); result.put("timestamp", df.format(ZonedDateTime.now())); return result; }); }
private Cancellable schedule() { FiniteDuration duration = Duration.create((long)((float)config.getLeafDecayDelay() / speed), TimeUnit.MILLISECONDS); return getContext().system().scheduler().schedule(duration, duration, getSelf(), new Trigger(), getContext().system().dispatcher(), getSelf()); }
private static void writeChunksAsync(final Chunks.Out<String> out, final Report r) { final Counter counter = new Counter(); final Cancellable job = Akka.system().scheduler().schedule(// Duration.create(0, TimeUnit.MILLISECONDS),// Duration.create(1, TimeUnit.SECONDS), // new Runnable() { @Override public void run() { String chunk = r.getChunk(counter.count++); Logger.info("Ecrit le chunk [{}]", chunk); if (chunk != null) { out.write(chunk); } else { out.close(); } } }, Akka.system().dispatcher()); // Stoppe le job après 10 secondes Akka.system().scheduler().scheduleOnce(// Duration.create(10, TimeUnit.SECONDS), // new Runnable() { public void run() { job.cancel(); } }, Akka.system().dispatcher()); }
private void schedule() { // set the email schedule to next full hour clock for sending daily and hourly emails Cancellable emailScheudler = system.scheduler().schedule( Duration.create(nextExecutionInSeconds(getNextHour(), 0), TimeUnit.SECONDS), Duration.create(1, TimeUnit.HOURS), () -> { emailService.sendDailyHourlyNotificationsEmails(); }, system.dispatcher() ); // cancel it on application stop lifecycle.addStopHook(() -> { emailScheudler.cancel(); return CompletableFuture.completedFuture(null); }); // Sets the schedule for cleaning the media temp directory Cancellable cleanUpScheudler = system.scheduler().schedule( Duration.create(0, TimeUnit.MILLISECONDS), Duration.create(2, TimeUnit.HOURS), () -> { mediaManager.cleanUpTemp(); }, system.dispatcher() ); // cancel it on application stop lifecycle.addStopHook(() -> { cleanUpScheudler.cancel(); return CompletableFuture.completedFuture(null); }); }
private Cancellable scheduleThrottler(final int initialDelay, final int msgsPerSecond, final int maxMsgsAtGivenTime) { return new Throttler(initialDelay, msgsPerSecond, maxMsgsAtGivenTime) { @Override public int getInProgressActionCount() { return (int)(db().getInprogressTasksCount()); } @Override public void runAction() { workerRouter.tell(EXECUTE_WORK, getSelf()); } }.startThrottling(); }
@Bean public Cancellable mainScheduler() { return actorSystem().scheduler().schedule( Duration.create(0, TimeUnit.SECONDS), Duration.create(SchedulerConfig.controllerInterval, TimeUnit.SECONDS), controlActorRef(), "Update", actorSystem().dispatcher(), null ); }
private void cancelTasks() { tasks.values().forEach(Cancellable::cancel); }
Cancellable newTimer(Object message) { return newTimer(raftContext.getConfigParams().getElectionTimeOutInterval().$times(2), message); }
Cancellable newTimer(FiniteDuration timeout, Object message) { return raftContext.getActorSystem().scheduler().scheduleOnce( timeout, raftContext.getActor(), message, raftContext.getActorSystem().dispatcher(), raftContext.getActor()); }
Persisting(ServerOperationContext<?> operationContext, Cancellable timer) { this.operationContext = operationContext; this.timer = timer; }
Cancellable newInstallSnapshotTimer() { return newTimer(new ServerOperationTimeout(addServerContext.getOperation().getNewServerId())); }
InstallingSnapshot(AddServerContext addServerContext, Cancellable installSnapshotTimer) { super(addServerContext); this.installSnapshotTimer = Preconditions.checkNotNull(installSnapshotTimer); }
WaitingForPriorSnapshotComplete(AddServerContext addServerContext, Cancellable snapshotTimer) { super(addServerContext); this.snapshotTimer = Preconditions.checkNotNull(snapshotTimer); }
private void cancelOwnerSelectionTask(final YangInstanceIdentifier entityPath) { final Cancellable lastScheduledTask = entityToScheduledOwnershipTask.get(entityPath); if (lastScheduledTask != null && !lastScheduledTask.isCancelled()) { lastScheduledTask.cancel(); } }
private void sendResponse(final ShardInformation shardInformation, final boolean doWait, final boolean wantShardReady, final Supplier<Object> messageSupplier) { if (!shardInformation.isShardInitialized() || wantShardReady && !shardInformation.isShardReadyWithLeaderId()) { if (doWait) { final ActorRef sender = getSender(); final ActorRef self = self(); Runnable replyRunnable = () -> sender.tell(messageSupplier.get(), self); OnShardInitialized onShardInitialized = wantShardReady ? new OnShardReady(replyRunnable) : new OnShardInitialized(replyRunnable); shardInformation.addOnShardInitialized(onShardInitialized); FiniteDuration timeout = shardInformation.getDatastoreContext() .getShardInitializationTimeout().duration(); if (shardInformation.isShardInitialized()) { // If the shard is already initialized then we'll wait enough time for the shard to // elect a leader, ie 2 times the election timeout. timeout = FiniteDuration.create(shardInformation.getDatastoreContext().getShardRaftConfig() .getElectionTimeOutInterval().toMillis() * 2, TimeUnit.MILLISECONDS); } LOG.debug("{}: Scheduling {} ms timer to wait for shard {}", persistenceId(), timeout.toMillis(), shardInformation.getShardName()); Cancellable timeoutSchedule = getContext().system().scheduler().scheduleOnce( timeout, getSelf(), new ShardNotInitializedTimeout(shardInformation, onShardInitialized, sender), getContext().dispatcher(), getSelf()); onShardInitialized.setTimeoutSchedule(timeoutSchedule); } else if (!shardInformation.isShardInitialized()) { LOG.debug("{}: Returning NotInitializedException for shard {}", persistenceId(), shardInformation.getShardName()); getSender().tell(createNotInitializedException(shardInformation.getShardId()), getSelf()); } else { LOG.debug("{}: Returning NoShardLeaderException for shard {}", persistenceId(), shardInformation.getShardName()); getSender().tell(createNoShardLeaderException(shardInformation.getShardId()), getSelf()); } return; } getSender().tell(messageSupplier.get(), getSelf()); }
Cancellable getTimeoutSchedule() { return timeoutSchedule; }