Lifecycle class abstract interface

A bean that runs something in the background between a start and a stop, such as a timer, a server or a connection.

Implement it so that the context can stop the background work: on context.stop(), on close() (before the beans are destroyed) and on pause(). A plain Lifecycle bean is not started at refresh, only by an explicit context.start(), or at refresh when an auto-startup bean depends on it. For a bean that should start by itself with the application, which is the usual case, use SmartLifecycle. Only singletons take part, and a lazy plain Lifecycle bean only once it was created.

// Polls every 5 seconds while the context runs.
@Component()
class Poller implements Lifecycle {
  Timer? _timer;

  @override
  void start() => _timer = Timer.periodic(
    const Duration(seconds: 5),
    (_) => poll(),
  );

  @override
  void stop() => _timer?.cancel();

  @override
  bool get isRunning => _timer?.isActive ?? false;
}

Spring (Java):

@Component
class Poller implements Lifecycle {
  public void start() { ... }
  public void stop() { ... }
  public boolean isRunning() { ... }
}

Properties

hashCode → int
The hash code for this object.
no setterinherited
isRunning → bool
Whether the background work is running; the context asks before starting or stopping the bean.
no setter
runtimeType → Type
A representation of the runtime type of the object.
no setterinherited

Methods

noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
start() → void
Starts the background work. The context does not call it when isRunning is already true; an error thrown here fails the start as an ApplicationContextException.
stop() → void
Stops the background work. The context calls it only when isRunning is true; an error thrown here is logged and the other beans are still stopped.
toString() → String
A string representation of this object.
inherited

Operators

operator ==(Object other) → bool
The equality operator.
inherited