runPeriodic method

String runPeriodic(
  1. Function runnable, {
  2. required Duration duration,
  3. Duration? delay,
  4. int? count,
  5. bool condition(
    1. int
    )?,
  6. String? tag,
})

周期执行

Implementation

String runPeriodic(
  Function runnable, {
  required Duration duration,
  Duration? delay,
  int? count,
  bool Function(int)? condition,
  String? tag,
}) {
  delay ??= duration;
  int count = 0;
  Timer? thread;

  // 周期运行程序
  doTask() {
    // 运行
    runnable.call();
    // 判断是否继续条件
    if (condition?.call(++count) == true) {
      // 从缓存中移除线程
      _threads.remove(thread);
      // 取消线程
      thread?.cancel();
      return false;
    }
    return true;
  }

  // 检查标签
  tag = _checkedTag(tag);

  /// 延时执行
  Timer? temp;
  temp = Timer(delay, () {
    // 移除历史线程
    _threads.remove(temp);
    // 判断任务执行结果
    if (doTask()) {
      /// 开始循环任务
      thread = Timer.periodic(duration, (t) => doTask());
      _threads.put(tag!, thread!);
    }
  });
  _threads.put(tag, temp);
  return tag;
}