Created
October 1, 2021 15:04
-
-
Save mj-hd/a6587808317d3d905373c43b04f83d4e to your computer and use it in GitHub Desktop.
backoff_stream.dart
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:math'; | |
Stream<int> linearBackoff({ | |
required int limit, | |
required num delay, | |
}) async* { | |
for (var i = 0; i < limit; i++) { | |
await Future.delayed(Duration(milliseconds: delay.floor())); | |
yield i; | |
} | |
} | |
Stream<int> exponentialBackoff({ | |
required int limit, | |
required num base, | |
num capacity = double.infinity, | |
num factor = 2, | |
}) async* { | |
final random = Random(); | |
for (var i = 0; i < limit; i++) { | |
final delay = random.nextDouble() * min(capacity, base * pow(factor, i)); | |
await Future.delayed(Duration(milliseconds: delay.floor())); | |
yield i; | |
} | |
} | |
void main() async { | |
final backoff = exponentialBackoff(limit: 5, base: 100, capacity: 1000); | |
DateTime prev = DateTime.now(); | |
await for (final i in backoff) { | |
final now = DateTime.now(); | |
print('retry#$i ${now.difference(prev).inMilliseconds}ms'); | |
prev = now; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment