addTask<T> method

Future<T> addTask<T>({
  1. required Future<T> task(),
  2. int priority = 0,
  3. String? taskName,
  4. void onStart()?,
  5. void onComplete(
    1. T result
    )?,
  6. void onError(
    1. dynamic error,
    2. StackTrace stackTrace
    )?,
})

Adds a task to the queue

task is the function to execute priority is the priority of the task (higher values = higher priority) taskName is an optional name for the task (for logging) onStart is an optional callback for when the task starts onComplete is an optional callback for when the task completes onError is an optional callback for when the task fails

Implementation

Future<T> addTask<T>({
  required Future<T> Function() task,
  int priority = 0,
  String? taskName,
  void Function()? onStart,
  void Function(T result)? onComplete,
  void Function(dynamic error, StackTrace stackTrace)? onError,
}) {
  final completer = Completer<T>();
  final name = taskName ?? 'Task-${DateTime.now().millisecondsSinceEpoch}';

  _logger.info('Adding task to queue: $name (priority: $priority)');

  final scrapingTask = _ScrapingTask<T>(
    task: task,
    completer: completer,
    priority: priority,
    name: name,
    onStart: onStart,
    onComplete: onComplete,
    onError: onError,
  );

  _pendingTasks.add(scrapingTask);
  _sortQueue();
  _processQueue();

  return completer.future;
}