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

# Background Execution

> Execute code in the background and return immediately with a process ID using the HopX VM Agent API. Run long-running code without blocking, monitor process status, and retrieve results when complete. Learn how to use POST /execute/background endpoint for asynchronous code execution. Includes request examples and process management.

Execute code in the background and return immediately. The code continues running asynchronously, and you can check its status using the process ID.

## Endpoint

```
POST /execute/background
```

## Request

### Headers

```
Authorization: Bearer YOUR_JWT_TOKEN
Content-Type: application/json
```

### Body Parameters

| Parameter     | Type    | Required | Description                                  |
| ------------- | ------- | -------- | -------------------------------------------- |
| `code`        | string  | Yes      | Code to execute                              |
| `language`    | string  | No       | Language (default: `python`)                 |
| `timeout`     | integer | No       | Max execution time in seconds (default: 300) |
| `working_dir` | string  | No       | Working directory                            |
| `env`         | object  | No       | Environment variables                        |
| `name`        | string  | No       | Process name for identification              |

### Example Request

```bash theme={null}
curl -X POST https://sandbox_abc123xyz.hopx.dev/execute/background \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "code": "import time\nfor i in range(10):\n    print(f\"Step {i+1}/10\")\n    time.sleep(1)\nprint(\"Done!\")",
    "language": "python",
    "name": "long-task"
  }'
```

## Response

### Success (200 OK)

```json theme={null}
{
  "process_id": "proc_abc123",
  "execution_id": "exec_xyz789",
  "status": "running"
}
```

### Response Fields

| Field          | Type   | Description                              |
| -------------- | ------ | ---------------------------------------- |
| `process_id`   | string | Process ID (use to check status or kill) |
| `execution_id` | string | Execution ID                             |
| `status`       | string | Initial status (`queued` or `running`)   |

## Status Codes

| Code | Description             |
| ---- | ----------------------- |
| 200  | Process started         |
| 400  | Invalid request         |
| 401  | Unauthorized            |
| 500  | Failed to start process |

## Check Process Status

Use the List Processes endpoint to check status:

```bash theme={null}
curl https://sandbox_abc123xyz.hopx.dev/execute/processes \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"
```

Response:

```json theme={null}
{
  "processes": [
    {
      "process_id": "proc_abc123",
      "execution_id": "exec_xyz789",
      "name": "long-task",
      "status": "running",
      "language": "python",
      "started_at": "2025-01-28T00:00:00Z",
      "stdout": "Step 1/10\nStep 2/10\n",
      "stderr": "",
      "exit_code": null
    }
  ],
  "count": 1
}
```

## Kill Background Process

Use the Kill Process endpoint to terminate:

```bash theme={null}
curl -X DELETE https://sandbox_abc123xyz.hopx.dev/execute/kill \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "process_id": "proc_abc123"
  }'
```

## Use Cases

### Long-Running Data Processing

```bash theme={null}
curl -X POST https://sandbox_abc123xyz.hopx.dev/execute/background \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "code": "import pandas as pd\nimport time\n\nprint(\"Processing large dataset...\")\ntime.sleep(30)\ndf = pd.read_csv(\"/workspace/large_file.csv\")\nresult = df.groupby(\"category\").sum()\nresult.to_csv(\"/workspace/result.csv\")\nprint(\"Processing complete!\")",
    "language": "python",
    "timeout": 600,
    "name": "data-processing"
  }'
```

### Model Training

```bash theme={null}
curl -X POST https://sandbox_abc123xyz.hopx.dev/execute/background \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "code": "from sklearn.ensemble import RandomForestClassifier\nimport numpy as np\nimport time\n\nprint(\"Training model...\")\nX = np.random.rand(10000, 20)\ny = np.random.randint(0, 2, 10000)\n\nmodel = RandomForestClassifier(n_estimators=100)\nmodel.fit(X, y)\n\nprint(f\"Model accuracy: {model.score(X, y):.2f}\")\nprint(\"Training complete!\")",
    "language": "python",
    "timeout": 1800,
    "name": "model-training"
  }'
```

### Monitoring Background Process

```bash theme={null}
#!/bin/bash
PROCESS_ID="proc_abc123"

while true; do
  STATUS=$(curl -s https://sandbox_abc123xyz.hopx.dev/execute/processes \
    -H "Authorization: Bearer YOUR_JWT_TOKEN" | \
    jq -r ".processes[] | select(.process_id == \"$PROCESS_ID\") | .status")
  
  echo "Status: $STATUS"
  
  if [ "$STATUS" == "completed" ] || [ "$STATUS" == "failed" ]; then
    echo "Process finished"
    break
  fi
  
  sleep 5
done
```

### Parallel Execution

```bash theme={null}
#!/bin/bash
# Start multiple background tasks
for i in {1..5}; do
  curl -X POST https://sandbox_abc123xyz.hopx.dev/execute/background \
    -H "Authorization: Bearer YOUR_JWT_TOKEN" \
    -H "Content-Type: application/json" \
    -d "{
      \"code\": \"import time\\ntime.sleep(10)\\nprint('Task $i complete')\",
      \"language\": \"python\",
      \"name\": \"task-$i\"
    }"
  
  echo "Started task $i"
done

echo "All tasks started, check status:"
curl https://sandbox_abc123xyz.hopx.dev/execute/processes \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"
```

## Related

* **SDK**: [sandbox.run\_code\_background()](/sdk/python/sandbox#run_code_background) - Python SDK method
* [CLI Code Execution](/cli/commands/run) - Execute code from CLI

## Next Steps

* **[List Processes](/api/vm-agent/list-processes)** - Check background process status
* **[Kill Process](/api/vm-agent/kill-process)** - Terminate a background process
* **[Async Execution](/api/vm-agent/execute-async)** - Execute with webhook callbacks
