Dart| Flutter How to: Run a function repeatedly with a delay

This tutorial shows multiple ways to execute a function repeatedly with a delay timer in dart and flutter programming.

How to execute function repeatedly with delay timer

There are multiple ways we can execute a code function periodically with delay time.

  • use the Timer Periodic method

First Create a Duration Object with one minute

The Timer.Periodic() method allows you to create a timer.

Timer Timer.periodic(Duration duration, void Function(Timer) callback)

It accepts Duration and Callback function parameters.

And, Executes the callback function for the duration timer repeatedly.

Here is an example of running a print statement repeatedly for every minute

import 'dart:async';

main() {
  const oneMinute = Duration(minutes: 1);
  Timer.periodic(oneMinute, (Timer t) {
    print('Hello Welcome:  ' + new DateTime.now().toString());
  });
}

Output:

Hello Welcome:  2022-03-30 09:42:52.810
Hello Welcome:  2022-03-30 09:43:52.825
Hello Welcome:  2022-03-30 09:44:52.814
Hello Welcome:  2022-03-30 09:45:52.818
Hello Welcome:  2022-03-30 09:47:26.838
Hello Welcome:  2022-03-30 09:48:26.815
Hello Welcome:  2022-03-30 09:49:26.814
Hello Welcome:  2022-03-30 09:50:26.840
Hello Welcome:  2022-03-30 09:51:26.823
Hello Welcome:  2022-03-30 09:52:26.810
Hello Welcome:  2022-03-30 09:53:26.830
Hello Welcome:  2022-03-30 09:54:26.847
  • use StreamSubscription Periodic class StreamSubscription class provides event subscription on Stream classes.

  • Create a stream using Stream.periodic() method

  • It creates a Stream that repeatedly emits the events for a period of duration object configured

Stream<dynamic> Stream.periodic(Duration period, [dynamic Function(int)? computation])
  • take(n) method on the Stream object allows for to execution of a count of n times.
  • listen() event catches the emit events and executes the function. Arrow functions are used to execute.
import 'dart:async';

main() {
  StreamSubscription streamSubscription;

  const oneSecond = Duration(seconds: 1);

  streamSubscription = new Stream.periodic(oneSecond)
      .take(5)
      .listen((_) => print('Hello Welcome:  ' + new DateTime.now().toString()));
}

Output:

Hello Welcome:  2022-03-30 10:29:29.211
Hello Welcome:  2022-03-30 10:29:30.209
Hello Welcome:  2022-03-30 10:29:31.209
Hello Welcome:  2022-03-30 10:29:32.209
Hello Welcome:  2022-03-30 10:29:33.813

This approach has more advantages compared with Timer.Periodic.

  • The first execution runs immediately
  • callback execution count can be configured and limited to n times.

Conclusion

To summarize, We can use Timer and Stream periodic methods to execute the function repeatedly with configured duration.