PeriodicTimer class

An alternative to Timer.periodic that ensures its callback is only being run once.

Using Timer.periodic can cause your function to run in parallel with itself. For example:

void main() => Timer.periodic(Duration(seconds: 1), twoSecondDelay);

void twoSecondDelay(_) async {
  final id = Random().nextInt(100);
  print("Starting task $id");
  await Future.delayed(Duration(seconds: 2));
  print("Finished tick $id");
}

Running the above code will cause twoSecondDelay to be started before the previous call has even finished. If your function uses a handle to a blocking resource, then the second call will crash or stall while the first one is still running. This class ensures that each call to function finishes running before the next one begins, while still making sure that they are called approximately every interval.

Constructors

PeriodicTimer(Duration interval, FutureOr<void> function())
Creates a periodic timer and starts the next tick asynchronously.

Properties

function FutureOr<void> Function()
The function to run. Can be synchronous or asynchronous.
final
hashCode int
The hash code for this object.
no setterinherited
interval Duration
The interval at which to run function.
final
isRunning bool
Whether this timer is currently running.
getter/setter pair
runtimeType Type
A representation of the runtime type of the object.
no setterinherited
stopwatch Stopwatch
A stopwatch that measures the time it takes to run function.
final
timer Timer?
A timer that runs the next _tick at exactly the right time.
getter/setter pair

Methods

cancel() → void
Cancels the timer.
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
restart() → void
Restarts the timer and begins the next tick asynchronously.
toString() String
A string representation of this object.
inherited

Operators

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