stop method

Future<void> stop([
  1. CancellationToken? cancellationToken
])

Attempts to gracefully stop the program.

Implementation

Future<void> stop([CancellationToken? cancellationToken]) async {
  _stopCalled = true;
  _logger.stopping();

  cancellationToken ??= CancellationToken.none;

  var cts = CancellationTokenSource(_options.shutdownTimeout);
  var linkedCts = CancellationTokenSource.createLinkedTokenSource(
    [
      cts.token,
      cancellationToken,
    ],
  );

  var token = linkedCts.token;
  // Trigger HostApplicationLifetime.applicationStopping
  _applicationLifetime.stopApplication();

  var exceptions = <Exception>[];
  if (_hostedServices != null) {
    for (var hostedService
        in List<HostedService>.from(_hostedServices!).reversed) {
      try {
        await hostedService.stop(token);
      } on Exception catch (ex) {
        exceptions.add(ex);
      }
    }
  }

  // Fire HostApplicationLifetime.stopped
  _applicationLifetime.notifyStopped();

  try {
    await _hostLifetime.stop(token);
  } on Exception catch (ex) {
    exceptions.add(ex);
  }

  if (exceptions.isNotEmpty) {
    var ex = Exception('One or more hosted services failed to stop.');
    _logger.stoppedWithException(ex);
    throw ex;
  }

  _logger.stopped();
}