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

# Background Tasks

> Run recipes and agents as background tasks in TypeScript

# Background Tasks (TypeScript)

Run recipes and agents asynchronously in the background with progress tracking, cancellation support, and result retrieval.

## Installation

```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
npm install praisonai-ts
```

## Basic Usage

### Running a Recipe in Background

```typescript theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
import { recipe } from 'praisonai-ts';

// Submit recipe as background task
const task = await recipe.runBackground('my-recipe', {
  input: { query: 'What is AI?' },
  config: { maxTokens: 1000 },
  sessionId: 'session_123',
  timeoutSec: 300,
});

console.log(`Task ID: ${task.taskId}`);
console.log(`Session: ${task.sessionId}`);

// Check status
const status = await task.status();
console.log(`Status: ${status}`);

// Wait for completion
const result = await task.wait(600);
console.log(`Result: ${result}`);

// Cancel if needed
await task.cancel();
```

### BackgroundTaskHandle Interface

```typescript theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
interface BackgroundTaskHandle {
  taskId: string;
  recipeName: string;
  sessionId?: string;
  
  status(): Promise<TaskStatus>;
  wait(timeout?: number): Promise<any>;
  cancel(): Promise<boolean>;
}

type TaskStatus = 'pending' | 'running' | 'completed' | 'failed' | 'cancelled';
```

## Using with Agents

```typescript theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
import { Agent, BackgroundRunner } from 'praisonai-ts';

// Create agent
const agent = new Agent({
  instructions: 'You are a helpful assistant',
  verbose: true,
});

// Create background runner
const runner = new BackgroundRunner({ maxConcurrentTasks: 5 });

// Submit task
const task = await runner.submit(
  () => agent.start('Analyze this data'),
  {
    name: 'analysis-task',
    timeout: 300,
  }
);

// Wait for result
const result = await runner.waitForTask(task.id);
```

## Configuration

### Safe Defaults

| Setting           | Default | Description                                |
| ----------------- | ------- | ------------------------------------------ |
| `timeoutSec`      | 300     | Maximum execution time (5 minutes)         |
| `maxConcurrent`   | 5       | Maximum concurrent tasks                   |
| `cleanupDelaySec` | 3600    | Time before completed tasks are cleaned up |

### Runtime Configuration

Configure 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

```typescript theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
import { recipe, RecipeError } from 'praisonai-ts';

try {
  const task = await recipe.runBackground('my-recipe', { input: 'test' });
  const result = await task.wait(60);
} catch (error) {
  if (error instanceof RecipeError) {
    console.error(`Recipe error: ${error.message}`);
  } else if (error.name === 'TimeoutError') {
    console.error('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/js/background-tasks-cli) - CLI commands
* [Async Jobs](/docs/js/async-jobs) - Server-based job execution
* [Scheduler](/docs/js/scheduler) - Periodic task scheduling
