Class BackgroundTask

java.lang.Object
com.alibaba.cloud.ai.graph.agent.tools.task.BackgroundTask

public class BackgroundTask extends Object
Manages the execution of a background task using CompletableFuture.

Provides thread-safe access to task status, results, and error information. Tasks are automatically started upon construction. Callers can check completion status, wait for completion, cancel tasks, and retrieve results or errors.

Author:
Spring AI Alibaba
  • Constructor Details

    • BackgroundTask

      public BackgroundTask(String taskId, CompletableFuture<String> future)
      Create a BackgroundTask with an existing future.
      Parameters:
      taskId - the task identifier
      future - the completable future to wrap
  • Method Details

    • isCompleted

      public boolean isCompleted()
      Check if the task has completed execution.
    • getResult

      public String getResult()
      Get the result of the task execution (non-blocking).
      Returns:
      the task result, or null if not yet completed or if an error occurred
    • getError

      public Exception getError()
      Get the error that occurred during task execution, if any.
    • getStatus

      public String getStatus()
      Get a human-readable status description of the task.
    • waitForCompletion

      public boolean waitForCompletion(long timeoutMs) throws InterruptedException
      Wait for the task to complete within the specified timeout.
      Parameters:
      timeoutMs - the maximum time to wait in milliseconds
      Returns:
      true if the task completed within the timeout, false if it timed out
      Throws:
      InterruptedException
    • cancel

      public boolean cancel(boolean mayInterruptIfRunning)
      Cancel the task if it hasn't completed yet.
    • getTaskId

      public String getTaskId()
      Get the task ID.