launch<T> method

String launch<T>({
  1. required String name,
  2. required TaskFunction<T> function,
  3. TaskPriority priority = TaskPriority.normal,
  4. Duration? timeout,
  5. String? id,
})

Launch a new task. Returns the task ID.

Implementation

String launch<T>({
  required String name,
  required TaskFunction<T> function,
  TaskPriority priority = TaskPriority.normal,
  Duration? timeout,
  String? id,
}) {
  if (_disposed) throw StateError('TaskManager is disposed');

  final taskId = id ?? 'task_${++_idCounter}';
  final task = BackgroundTask<T>(
    id: taskId,
    name: name,
    function: function,
    priority: priority,
    timeout: timeout,
  );

  _tasks[taskId] = task;
  _eventController.add(TaskCreated(taskId, name));
  task.log.info('Task created with priority ${priority.name}');

  if (_runningCount < maxConcurrent) {
    _startTask(taskId);
  } else {
    task._status = TaskStatus.queued;
    _insertIntoQueue(taskId, priority);
    task.log.info('Task queued (${_queue.length} in queue)');
    _eventController.add(TaskQueued(taskId));
  }

  return taskId;
}