> ## Documentation Index
> Fetch the complete documentation index at: https://praison.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Background Tasks

> Run recipes and agents as background tasks with progress tracking

# Background Tasks

Background tasks allow you to run recipes and agents asynchronously without blocking your main application. Tasks run in the background with full progress tracking, cancellation support, and result retrieval.

## Python API

### Running a Recipe in Background

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonai import recipe

# Submit recipe as background task
task = recipe.run_background(
    "my-recipe",
    input={"query": "What is AI?"},
    config={"max_tokens": 1000},
    session_id="session_123",
    timeout_sec=300,
)

print(f"Task ID: {task.task_id}")
print(f"Session: {task.session_id}")

# Check status
status = await task.status()
print(f"Status: {status}")

# Wait for completion
result = await task.wait(timeout=600)
print(f"Result: {result}")

# Cancel if needed
await task.cancel()
```

### BackgroundTaskHandle

The `run_background()` function returns a `BackgroundTaskHandle` with these methods:

| Method          | Description                                   |
| --------------- | --------------------------------------------- |
| `task_id`       | Unique task identifier                        |
| `recipe_name`   | Name of the recipe being executed             |
| `session_id`    | Session ID for conversation continuity        |
| `status()`      | Get current task status (async)               |
| `wait(timeout)` | Wait for completion and return result (async) |
| `cancel()`      | Cancel the running task (async)               |

### Task Status Values

* `pending` - Task is queued but not started
* `running` - Task is currently executing
* `completed` - Task finished successfully
* `failed` - Task failed with an error
* `cancelled` - Task was cancelled

### Using with Agents Directly

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent
from praisonaiagents.background import BackgroundRunner

# Create agent
agent = Agent(
    instructions="You are a helpful assistant",
    
)

# Create background runner
runner = BackgroundRunner(max_concurrent_tasks=5)

# Submit task
task = await runner.submit(
    lambda: agent.start("Analyze this data"),
    name="analysis-task",
    timeout=300,
)

# Wait for result
result = await runner.wait_for_task(task.id)
```

## Configuration

### Safe Defaults

Background tasks use safe defaults to prevent runaway execution:

| Setting             | Default | Description                                |
| ------------------- | ------- | ------------------------------------------ |
| `timeout_sec`       | 300     | Maximum execution time (5 minutes)         |
| `max_concurrent`    | 5       | Maximum concurrent tasks                   |
| `cleanup_delay_sec` | 3600    | Time before completed tasks are cleaned up |

### TEMPLATE.yaml Runtime Block

Configure background task defaults in your recipe's `TEMPLATE.yaml`:

```yaml theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
runtime:
  background:
    enabled: true
    max_concurrent: 3
    cleanup_delay_sec: 3600
```

## Error Handling

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonai import recipe
from praisonai.recipe import RecipeError

try:
    task = recipe.run_background("my-recipe", input="test")
    result = await task.wait(timeout=60)
except RecipeError as e:
    print(f"Recipe error: {e}")
except TimeoutError:
    print("Task timed out")
    await task.cancel()
```

## Best Practices

1. **Always set timeouts** - Prevent tasks from running indefinitely
2. **Use session IDs** - Track related tasks across executions
3. **Handle cancellation** - Clean up resources when tasks are cancelled
4. **Monitor progress** - Use status checks for long-running tasks
5. **Limit concurrency** - Don't overwhelm system resources

## See Also

* [Background Tasks CLI](/docs/sdk/praisonai/cli/background-tasks-cli) - CLI commands for background tasks
* [Async Jobs](/docs/sdk/praisonai/async-jobs) - Server-based job execution
* [Scheduler](/docs/sdk/praisonai/scheduler) - Periodic task scheduling
