Skip to content

Instantly share code, notes, and snippets.

@sombochea
Created February 16, 2024 05:55
Show Gist options
  • Save sombochea/07bea3483b2b6585e1e42e83b5ab4adb to your computer and use it in GitHub Desktop.
Save sombochea/07bea3483b2b6585e1e42e83b5ab4adb to your computer and use it in GitHub Desktop.
A simple code for run with retry and concurrently in dart.
import 'dart:async';
import 'dart:collection';
FutureOr<T?> executeWithRetry<T>(
FutureOr<T?> Function() function, {
int maxRetries = 3,
int delayFactor = 2, // in seconds
throwIfFailed = true,
}) async {
int retries = 0;
while (retries < maxRetries) {
try {
return await function();
} catch (e) {
await Future.delayed(Duration(seconds: retries * delayFactor));
retries++;
if (retries == maxRetries) {
if (throwIfFailed) {
rethrow;
}
}
}
}
// nothing to return
return null;
}
Future<void> runConcurrently(
List<Function> functions, {
int maxTasks = 4,
int maxRetries = 1,
int delayFactor = 0, // in seconds
bool throwIfFailed = true,
}) async {
final queue = Queue<FutureOr<void> Function()>.from(functions);
final futures = <Future>[];
while (queue.isNotEmpty) {
final tasks = queue.take(maxTasks).toList();
queue.removeWhere((element) => tasks.contains(element));
for (final task in tasks) {
futures.add(Future(() async {
await executeWithRetry(task,
maxRetries: maxRetries,
delayFactor: delayFactor,
throwIfFailed: throwIfFailed);
}));
}
await Future.wait(futures);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment