ScheduledFuture<T> constructor

ScheduledFuture<T>(
  1. DateTime timepoint, [
  2. FutureOrResultCallback<T>? computation
])

Creates a ScheduledFuture that is scheduled to run its computation at a specific point in time.

The computation will be executed when the current date and time equal timepoint, and the future is completed with the result of the computation.

If computation returns a future, the future returned by this constructor will complete with the value or error of that future.

If timepoint is now, or before now, it completes no sooner than in the next event-loop iteration, after all microtasks have run.

If computation is omitted, it will be treated as if computation was () => null, and the future will eventually complete with the null value. In that case, T must be nullable.

If calling computation throws, the created future will complete with the error.

Example:

final timepoint = DateTime.now();
const delay = Duration(seconds: 30);
ScheduledFuture(timepoint.add(delay), () {
  final birthedAt = DateTime.now().substract(delay);

  // Prints [timepoint].
  print("The future was created at $birthedAt");
});

Implementation

ScheduledFuture(
  DateTime timepoint, [
  FutureOrResultCallback<T>? computation,
]) {
  final now = clock.now();

  if (timepoint.isBefore(now) || timepoint.isAtSameMomentAs(now)) {
    // Using [Future.delayed] constructor instead of default [Future]
    // constructor, because this specialized constructor does some internal
    // type checking of `T` to ensure that [computation] is not null, if
    // `T` is not nullable.
    _inner = Future<T>.delayed(Duration.zero, computation);
  } else {
    final delay = timepoint.toUtc().difference(now.toUtc());
    assert(!delay.isNegative);
    _inner = Future<T>.delayed(delay, computation);
  }
}