# Run Commands in Background
<subtitle>Asynchronously execute long tasks in sandboxes and get their runtime status and output streams in real-time.</subtitle>

## Environment Setup

Before using the SDK, please ensure that the `AGENTBOX_API_KEY` environment variable is configured.

>
> You can obtain your API key from the [Console API Keys page](https://console.ucloud.cn/modelverse/experience/api-keys).

```bash
export AGENTBOX_API_KEY=your_api_key
```

For tasks that take a long time and do not need to block the main thread, you can run commands in the background by setting `background=True`.

## Start Async Task

Call the `run` method and specify the `background` parameter. It will immediately return a `Command` process handle.

```python
from ucloud_sandbox import Sandbox

sandbox = Sandbox.create()

# Start a long-running command in background
process = sandbox.commands.run('sleep 5; echo "Task Complete"', background=True)

# Main thread can continue executing other logic
print(f"Command started with PID: {process.pid}")
```

## Interaction and Monitoring

### Iterate Real-Time Output
You can get real-time output from background commands like iterating a generator.

```python
for stdout, stderr, _ in process:
    if stdout:
        print(f"[STDOUT]: {stdout}")
    if stderr:
        print(f"[STDERR]: {stderr}")
```

### Force Kill Background Task
If the task times out or is no longer needed, please release resources promptly.

```python
# Immediately terminate background running command
process.kill()
```

---

>
> **Wait for Completion**: If you need to ensure a background task completes at the end of your program, you can call `process.wait()`.
