private async ValueTask <Consumer <T> > PatternTopicSubscribe <T>(ConsumerConfigurationData <T> conf, ISchema <T> schema) { var regex = conf.TopicsPattern.ToString(); var subscriptionMode = ConvertRegexSubscriptionMode(conf.RegexSubscriptionMode); var destination = TopicName.Get(regex); var namespaceName = destination.NamespaceObject; IActorRef consumer = null; try { var ask = await _lookup.Ask <AskResponse>(new GetTopicsUnderNamespace(namespaceName, subscriptionMode.Value)).ConfigureAwait(false); if (ask.Failed) { throw ask.Exception; } var result = ask.ConvertTo <GetTopicsUnderNamespaceResponse>(); var topics = result.Topics; if (_actorSystem.Log.IsDebugEnabled) { _actorSystem.Log.Debug($"Get topics under namespace {namespaceName}, topics.size: {topics.Count}"); topics.ForEach(topicName => _actorSystem.Log.Debug($"Get topics under namespace {namespaceName}, topic: {topicName}")); } var topicsList = TopicsPatternFilter(topics, conf.TopicsPattern); topicsList.ToList().ForEach(x => conf.TopicNames.Add(x)); var state = _actorSystem.ActorOf(Props.Create(() => new ConsumerStateActor()), $"StateActor{Guid.NewGuid()}"); consumer = _actorSystem.ActorOf(PatternMultiTopicsConsumer <T> .Prop(conf.TopicsPattern, state, _client, _lookup, _cnxPool, _generator, conf, schema, subscriptionMode.Value, _clientConfigurationData), $"MultiTopicsConsumer{DateTimeHelper.CurrentUnixTimeMillis()}"); var response = await consumer.Ask <AskResponse>(new SubscribeAndCreateTopicsIfDoesNotExist(conf.TopicNames.ToList(), true)).ConfigureAwait(false); if (response.Failed) { await consumer.GracefulStop(TimeSpan.FromSeconds(5)); throw response.Exception; } _client.Tell(new AddConsumer(consumer)); return(new Consumer <T>(state, consumer, schema, conf)); } catch (Exception e) { if (consumer != null) { await consumer.GracefulStop(TimeSpan.FromSeconds(5)); } _actorSystem.Log.Warning($"[{namespaceName}] Failed to get topics under namespace"); throw e; } }
public void Dispose() { const long WAITMS = 1000; foreach (var item in InProgressQ) { var tcs = item.Value; tcs.SetCanceled(); } InProgressQ.Clear(); var closeList = new List <Task <bool> >(); if (ParseCoordinator != null) { closeList.Add(ParseCoordinator.GracefulStop(TimeSpan.FromMilliseconds(WAITMS))); ParseCoordinator = null; } if (DownloadCoordinator != null) { closeList.Add(DownloadCoordinator.GracefulStop(TimeSpan.FromMilliseconds(WAITMS))); DownloadCoordinator = null; } if (closeList.Count > 0) { Task.WaitAll(closeList.ToArray()); } AllTheWorld.Terminate().Wait(); allTheWorld = null; // force any new usage to start over }
public RequestProducer(int numberOfWorkers, string[] uris) { this.numberOfWorkers = numberOfWorkers; this.uris = uris; logger = Context.ActorOf<RequestLogger>("consoleLogger"); Receive<NewWorker>(worker => { log.Debug("Adding http request worker: {Worker}", Sender); //Console.WriteLine("Adding worker: " + Sender.Path); workers.Add(Sender); RequestHttpWork(Sender); }); Receive<Result>(worker => { logger.Tell(worker); RequestHttpWork(Sender); }); Receive<StopGenerationOfRequests>(stop => { Task.WaitAll(workerPool.GracefulStop(TimeSpan.FromSeconds(60)), logger.GracefulStop(TimeSpan.FromSeconds(60))); Sender.Tell("Done", Self); }); }
protected void StartSendProbe() { Task.Run(() => { int count = 1; Console.WriteLine("*** Start of sending probe"); do { probeClient.Tell(new SayRequest() { Text = $"Probe no {count}", }); Console.Write("."); count++; Thread.Sleep(1000); } while (!sendProbe.IsCancellationRequested); probeClient.GracefulStop(TimeSpan.FromMilliseconds(100)) .ContinueWith(r => Console.WriteLine($"Client stop with {r.Result}")); Console.WriteLine("*** End of sending probe"); // stopping Actor System actorSystem.Terminate(); } , sendProbe.Token ); }
protected override void PostStop() { _lookup.GracefulStop(TimeSpan.FromSeconds(1)); _cnxPool.GracefulStop(TimeSpan.FromSeconds(1)); _conf.Authentication = null; base.PostStop(); }
/// <inheritdoc/> public override Task <bool> Shutdown() { var stopTask = manager.GracefulStop((RARP.For(System).Provider).RemoteSettings.FlushWait); var transportStopTask = WrappedTransport.Shutdown(); return(Task.WhenAll(stopTask, transportStopTask).ContinueWith(x => x.IsCompleted && !(x.IsFaulted || x.IsCanceled), TaskContinuationOptions.ExecuteSynchronously)); }
/// <summary> /// Disconnects from the transport layer /// </summary> /// <param name="obj">Incoming message</param> private void DisconnectFromTransport(DisconnectProtocol obj) { _transport.Tell(DisconnectTransport.Instance, Self); _flightRecorder.GracefulStop(TimeSpan.FromMilliseconds(10)); Become(Disconnected); }
public override Task <bool> Shutdown() { var stopTask = manager.GracefulStop(((RemoteActorRefProvider)((ActorSystemImpl)System).Provider).RemoteSettings.FlushWait); var transportStopTask = WrappedTransport.Shutdown(); return(Task.WhenAll(stopTask, transportStopTask).ContinueWith(x => x.IsCompleted, TaskContinuationOptions.ExecuteSynchronously)); }
public void Dispose() { // give it a chance to cleanup _reporterActorRef.GracefulStop(TimeSpan.FromSeconds(5)).Wait(); // then optionally terminate ActorSystem _ownedActorSystem?.Terminate().Wait(); }
public void OnStop(StopRequest request) { _actionPipeline .GracefulStop(TimeSpan.FromSeconds(10)) .Wait(); _state = ActionProcessorState.Stopped; Sender.Tell(new Response(_state.ToString(), request)); }
public void Stop() { _sportsbook.GracefulStop(TimeSpan.FromSeconds(1)); Console.WriteLine("MemoryWallet stopped."); _system.Terminate(); Console.WriteLine("Actor System Terminated"); Environment.Exit(0); }
public void Dispose() { // give it a chance to cleanup var stop1 = _counterAggregatorRef.GracefulStop(TimeSpan.FromSeconds(5)); var stop2 = _reporterActorRef.GracefulStop(TimeSpan.FromSeconds(5)); Task.WaitAll(stop1, stop2); // then optionally terminate ActorSystem _ownedActorSystem?.Dispose(); }
private void ReleaseConnection(IActorRef cnx) { if (_maxConnectionsPerHosts == 0) { if (_log.IsDebugEnabled) { _log.Debug("close connection due to pooling disabled."); } cnx.GracefulStop(TimeSpan.FromSeconds(5)); } }
private static void FlushLogMessages() { try { _logger.GracefulStop(TimeSpan.FromSeconds(2)).Wait(); } catch { Console.WriteLine("Exception thrown while waiting for TCP transport to flush - not all messages may have been logged."); } }
public CoordinatorActor() { Receive <Messages.StartSession>(message => { if (Context.Child(message.GroupName).IsNobody()) { Console.WriteLine("{0} - {1}", message.GetType().Name, Context.Self.Path.ToStringWithAddress()); IActorRef group = Context.ActorOf(Props.Create <GroupActor>(), message.GroupName); group.Ask(message).PipeTo(Sender); } }); Receive <Messages.IncrementState>(message => { Console.WriteLine("{0} - {1}", message.GetType().Name, Context.Self.Path.ToStringWithAddress()); IActorRef group = Context.Child(message.GroupName); group.Tell(message); }); Receive <Messages.DecrementState>(message => { Console.WriteLine("{0} - {1}", message.GetType().Name, Context.Self.Path.ToStringWithAddress()); IActorRef group = Context.Child(message.GroupName); group.Tell(message); }); Receive <Messages.GroupEnded>(message => { Console.WriteLine("{0} - {1}", message.GetType().Name, Context.Self.Path.ToStringWithAddress()); IActorRef group = Context.Child(message.GroupName); if (!group.IsNobody()) { var gs = group.GracefulStop(TimeSpan.FromSeconds(30)); gs.Wait(); } ; }); Receive <Messages.QueryUserActorState>(message => { Console.WriteLine("{0} - {1}", message.GetType().Name, Context.Self.Path.ToStringWithAddress()); //This is used to check the existence of the group and if the group did not exist then //it could either spin up the actor in question then forward the message or send a failure //message to a track the error or just return a null message. IActorRef group = Context.Child(message.GroupName); var handler = GetSelection(message.GroupName, message.UserName); handler. Ask <Messages. QueryUserActionStateResult>(message). PipeTo(Sender); }); }
public static void Stop(TimeSpan timeout) { SendTerminateSignal(); _electionCycle?.GracefulStop(timeout); _electionCycle = null; _heartbeat?.GracefulStop(timeout); _heartbeat = null; _candidate?.GracefulStop(timeout); _candidate = null; _follower?.GracefulStop(timeout); _follower = null; }
private async static Task TerminateByUsingGracefulStop() { ActorSystem system = ActorSystem.Create("my-first-akka"); IActorRef emailSender = system.ActorOf <EmailSenderActor>("emailSender"); EmailMessage emailMessage = new EmailMessage("*****@*****.**", "*****@*****.**", "Hi"); emailSender.Tell(emailMessage); var result = emailSender.GracefulStop(TimeSpan.FromSeconds(10)); Thread.Sleep(1000); system.Terminate(); }
private void _stopMarket() { // 关闭所有的Actor foreach (var key in secActors.Keys) { _log.Debug("关闭Symbol {0} Actor", key); secActors[key].GracefulStop(TimeSpan.FromSeconds(5)); } secActors.Clear(); // quotationActor.Tell(""); // 关闭接收数据 _log.Debug("关闭行情接收器 Actor"); quotationActor.GracefulStop(TimeSpan.FromSeconds(5)); }
public override async Task Stop() { // stop gateway if (_gateway != null) { await _gateway.CastToIActorRef().GracefulStop( TimeSpan.FromSeconds(10), InterfacedMessageBuilder.Request <IGateway>(x => x.Stop())); } // stop game container await _gameContainer.GracefulStop(TimeSpan.FromSeconds(10), PoisonPill.Instance); }
/// <summary> /// Handle the message "JobFailedMessage" received from Worker /// </summary> /// <param name="job">message</param> private void HandleJobFailed(JobFailedMessage job) { ColorConsole.WriteLineMagenta("Task {0} of Coordinator {1} failed.", job.ID, Self.Path.Name); // send response to parent - commander _parent.Tell(job); // move to next state BecomeWaiting(); if (job.Status == JobStatus.Timeout) { //Context.Stop(_taskWorker); var shutdown = _taskWorker.GracefulStop(TimeSpan.FromMilliseconds(5)); InitializeWorker("worker_" + job.ID.ToString() + "_" + job.TimeOut.ToString()); } }
private void CreateNewClient() { // if probeClient previously already exist. if (chatClient is object) { chatClient.GracefulStop(TimeSpan.FromMilliseconds(100)).Wait(); Context.Unwatch(chatClient); } // create the new chatClient = Context.ActorOf(Props.Create <ProbeClientActor>("10.30.12.13", 8081, user)); Context.Watch(chatClient); // start monitoring the events... // Listen for Association Context.System.EventStream.Subscribe <AssociatedEvent>(chatClient); }
public async Task <bool> Close(ActorSystem context) { //Test run has already been closed or hasn't started if (!IsOpen || IsClosed) { return(await Task.FromResult(false)); } IsOpen = false; IsClosed = true; //Signal that the test run has ended return(await MessageSinkActorRef.Ask <MessageSinkActor.SinkCanBeTerminated>(new EndTestRun()) .ContinueWith(tr => MessageSinkActorRef.GracefulStop(TimeSpan.FromSeconds(2)), TaskContinuationOptions.ExecuteSynchronously).Unwrap()); }
public ExampleRootActor1(IActorRef rootActor2) { rootActor2.Tell("1"); rootActor2.Tell("2"); try { // // RootActor2는 현재 한 메시지를 처리하는 시간이 2초다. // 그러므로 // "2개 메시지 * 2초 = 총 4초" 시간이 소요된다. // // // Case1 : 시간내에 Actor가 종료할 때(성공) // // GracefulStop 함수를 호출할 때 10초 내로 Actor 종료를 기대한다. // 10초는 RootActor2가 모든 메시지를 처리하고 종료할 때까지 충분한 시간이다. // 그 결과 "true"가 리턴된다. // rootActor2.GracefulStop(TimeSpan.FromSeconds(10)).Wait(); // // Case2. : 시간내에 Actor가 종료하지 못할 때(실패) // // GracefulStop 함수를 호출할 때 3초 내로 Actor 종료를 기대한다. // RootActor2는 모든 메시지를 처리하는대 총 4초가 필요하기 때문에 // 그 결과 TaskCanceledException 예외가 발생한다. // //rootActor2.GracefulStop(TimeSpan.FromSeconds(3)).Wait(); } catch (AggregateException e) { foreach (TaskCanceledException innerEx in e.InnerExceptions) { // RootActor2는 모든 메시지를 처리하는대 총 4초가 필요하기 때문에 // 3초안에 종료할 수 없다. // 그 결과 예외가 발생된다. Console.WriteLine( string.Format("{0:000} {1,-40} : {2}", Thread.CurrentThread.ManagedThreadId, "ExampleRootActor1 AggregateException", innerEx)); } } }
private static ActorSystem ClaimHandlingSystem; // Change to better naming static async Task Main(string[] args) { ClaimHandlingSystem = ActorSystem.Create("ClaimHandlingSystem"); Console.ForegroundColor = ConsoleColor.DarkGreen; Console.WriteLine("Claim Handling System is up!"); Console.ForegroundColor = ConsoleColor.White; Props claimFetchProps = Props.Create <ClaimFetcherActor>(); Props openClaimProps = Props.Create <OpenClaimActor>(); IActorRef claimFetcherActorRef = ClaimHandlingSystem.ActorOf(claimFetchProps, "claimFetcher"); IActorRef claimOpenerActorRef = ClaimHandlingSystem.ActorOf(openClaimProps, "claimOpener"); claimFetcherActorRef.Tell(new FetchClaimMessage(Guid.NewGuid())); claimFetcherActorRef.Tell(new FetchClaimMessage(Guid.NewGuid())); claimOpenerActorRef.Tell(new ManualOpenClaimMessage(0, 0)); // Won't be handled claimOpenerActorRef.Tell(new ManualOpenClaimMessage(4000, 2019)); claimOpenerActorRef.Tell(new AutomaticallyOpenClaimMessage(5000, 2019)); Console.ReadKey(); // Tells the actor to shutdown, BUT first deal with all the messages in it's mail box claimFetcherActorRef.Tell(PoisonPill.Instance); // Gracefully stop the actor, awaiting 5 seconds. If more time passes, throw exception await claimOpenerActorRef.GracefulStop(TimeSpan.FromSeconds(5)); Console.ReadKey(); await ClaimHandlingSystem.Terminate(); Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine("Claim Handling System is down!"); Console.ForegroundColor = ConsoleColor.White; Console.ReadKey(); }
/// <summary> /// Completes the current print job /// </summary> /// <param name="_"></param> private void FinishPrintJob(PrintJobCompleted _) { _currentJob.GracefulStop(TimeSpan.FromMilliseconds(50)); UnbecomeStacked(); }
public override async Task Stop() { await _userTable.GracefulStop( TimeSpan.FromMinutes(1), new DistributedActorTableMessage <long> .GracefulStop(InterfacedPoisonPill.Instance)); }
protected override void PostStop() { _consumer.GracefulStop(TimeSpan.FromSeconds(1)); base.PostStop(); }
public override async Task Stop() { await _gamePairMaker.GracefulStop(TimeSpan.FromMinutes(1), InterfacedPoisonPill.Instance); }
protected override void OnReceive(object message) { // actually every message activates the reader var text = System.Console.ReadLine(); switch (text) { case QuitCommand: _consoleUi.Tell("terminate"); return; case StopCommand: // Actor receives the Stop message and suspends the actor’s Mailbox (other messages will go to DeadLetters). // Actor tells all its children to Stop. Stop messages propagate down the hierarchy below the actor. // Actor waits for all children to stop. // Actor calls PostStop lifecycle hook method for resource cleanup. // Actor shuts down. Context.Stop(_commandHandler); break; case PoisonPillCommand: // Use a PoisonPill message if you want the actor to process its mailbox before shutting down. // PoisonPill is a message that will be placed in the mailbox. // When the Actor process the message the above mentioned stop sequence will be initiated. _commandHandler.Tell(PoisonPill.Instance); break; case KillCommand: // Use a Kill message if you want it to show in your logs that the actor was killed. // The actor throws an ActorKilledException. The actor’s supervisor logs this message. // This suspends the actor mailbox from processing further user messages. // The actor’s supervisor handles the ActorKilledException and issues a Stop directive. // The actor will stop following the above mentioned stop sequence. _commandHandler.Tell(Kill.Instance); break; case GracefulStopCommand: // If you want confirmation that the actor was stopped within a specified Timespan. // It will return a Task<bool> you can check to know if the Actor was stopped. var gracefulStop = _commandHandler.GracefulStop(TimeSpan.FromSeconds(5)); gracefulStop.Wait(); if (gracefulStop.Result) { ColoredConsole.WriteLineGreen("GracefulStop completed"); } else { ColoredConsole.WriteLineYellow("GracefulStop failed"); } break; case EscalateExceptionCommand: _commandHandler.Tell(new EscalateExceptionCommand()); break; case RestartExceptionCommand: _commandHandler.Tell(new RestartExceptionCommand()); break; case ResumeExceptionCommand: _commandHandler.Tell(new ResumeExceptionCommand()); break; case StopExceptionCommand: _commandHandler.Tell(new StopExceptionCommand()); break; case DumpStatusCommand: _commandHandler.Tell(new DumpStatusCommand()); break; default: _commandHandler.Tell(text); break; } // send a message to outself stating we are ready to read the next command Self.Tell("readnext"); // we have no unhandled message here, every message will activare the read cycle again. }
protected override void OnReceive(object message) { var text = Console.ReadLine(); // Parse the Command (not production code! :D) // First check the stop/kill commands directed to the router switch (text) { case QuitCommand: _consoleUi.Tell("terminate"); return; case StopCommand: // Send a System Stop message to the specified actor (the message will have priority over others already in the mailbox). // Actor receives the Stop message and suspends the actor’s Mailbox (other messages will go to DeadLetters). // Actor tells all its children to Stop. Stop messages propagate down the hierarchy below the actor. // Actor waits for all children to stop. // Actor calls PostStop lifecycle hook method for resource cleanup. // Actor shuts down. Context.Stop(_commandHandler); ReadNext(); return; case PoisonPillCommand: // Use a PoisonPill message if you want the actor to process its mailbox before shutting down. // PoisonPill is a message that will be placed in the mailbox. // When the Actor process the message the above mentioned stop sequence will be initiated. _commandHandler.Tell(PoisonPill.Instance); ReadNext(); return; case KillCommand: // Use a Kill message if you want it to show in your logs that the actor was killed. // Send a System Kill message to the specified actor. // The actor throws an ActorKilledException (The actor’s supervisor logs this message). // This suspends the actor mailbox from processing further user messages. // The actor’s supervisor handles the ActorKilledException and issues a Stop directive. // The actor will stop following the above mentioned stop sequence. _commandHandler.Tell(Kill.Instance); ReadNext(); return; case GracefulStopCommand: // If you want confirmation that the actor was stopped within a specified Timespan. // It will send a PoisonPill message and 'start a timer to check if the actor stops within the specified amount of time'. // It will return a Task<bool> you can wait on to know if the Actor was stopped. // The Task can be cancelled if the Actor does not stop with the specified TimeSpan. try { var gracefulStop = _commandHandler.GracefulStop(TimeSpan.FromSeconds(5)); gracefulStop.Wait(); ColoredConsole.WriteLineGreen("GracefulStop completed"); } catch (AggregateException ex) { // the GracefulStop can fail if it cannot complete within the specified TimeSpan. // The Task will be cancelled. ColoredConsole.WriteLineYellow($"GracefulStop failed, exception: {ex}"); } ReadNext(); return; } // Try to parse the User Commands: 'UserId command' var parsedText = text.Split(' '); if (parsedText.Length == 2) { Command cmd; switch (parsedText[1]) { case EscalateExceptionCommand: cmd = new EscalateExceptionCommand(); break; case RestartExceptionCommand: cmd = new RestartExceptionCommand(); break; case ResumeExceptionCommand: cmd = new ResumeExceptionCommand(); break; case StopExceptionCommand: cmd = new StopExceptionCommand(); break; case PauseCommandHandlerCommand: cmd = new PauseCommandHandlerCommand(); break; case ResumeCommandHandlerCommand: cmd = new ResumeCommandHandlerCommand(); break; default: // Tell something! cmd = new InputCommand(parsedText[1]); /* * // Ask something! * ColoredConsole.WriteLineYellow("Awaiting for the command to complete"); * var completedTask = _commandHandler.Ask<InputCommandResponse>(new InputCommandRequest(parsedText[1])); * completedTask.Wait(); // blocking operation: wait for completion and a specific reply * ColoredConsole.WriteLineYellow($"Response: {completedTask.Result.Data}"); * ColoredConsole.WriteLineYellow("The command has been completed"); */ break; } cmd.Context.UserId = parsedText[0]; _commandHandler.Tell(cmd); } else { ReportUnsupportedCommand(text); } ReadNext(); // we have no unhandled message here, every message will activare the read cycle again. }
public override async Task Stop() { await _botContainer.GracefulStop(TimeSpan.FromSeconds(10), PoisonPill.Instance); }