Created
February 16, 2024 05:55
-
-
Save sombochea/07bea3483b2b6585e1e42e83b5ab4adb to your computer and use it in GitHub Desktop.
A simple code for run with retry and concurrently in 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: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