> ## 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

> Execute code in the background without blocking. Learn how to run long-running code in HopX sandboxes asynchronously, monitor background processes, retrieve results when complete, and manage process lifecycle. Perfect for training models, processing large datasets, or running time-consuming operations. Includes Python and JavaScript SDK examples.

Background execution allows you to start code execution and return immediately, without waiting for completion. This is ideal for long-running tasks that you want to monitor and manage separately.

## Prerequisites

Before you begin, make sure you have:

* **Active sandbox** - A running sandbox (see [Creating Sandboxes](/core-concepts/sandboxes/creating))
* **Understanding of synchronous execution** - Familiarity with [Synchronous Execution](/core-concepts/code-execution/synchronous) is helpful
* **Long-running task** - Code that takes more than a few minutes to complete

## Overview

Background execution is perfect for:

* Long-running computations (>5 minutes)
* Tasks that don't need immediate results
* Parallel processing of multiple tasks
* Workflows where you want to check status periodically

<Note>
  Background execution returns immediately with a `process_id`. Use [Process Management](/core-concepts/code-execution/process-management) to check status and manage background processes.
</Note>

## Starting Background Execution

Start code execution in the background:

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    from hopx_ai import Sandbox

    sandbox = Sandbox.create(template="code-interpreter")

    # Start background execution
    result = sandbox.run_code_background(
        code='''
    import time
    for i in range(10):
        print(f"Step {i+1}/10")
        time.sleep(2)
    print("Done!")
    ''',
        language='python',
        name='long-task'
    )

    process_id = result['process_id']
    print(f"Process started: {process_id}")
    print(f"Status: {result['status']}")

    sandbox.kill()
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    import { Sandbox } from '@hopx-ai/sdk';

    const sandbox = await Sandbox.create({ template: 'code-interpreter' });

    // Start background execution
    const result = await sandbox.runCodeBackground(
      `
    import time
    for i in range(10):
        print(f"Step {i+1}/10")
        time.sleep(2)
    print("Done!")
    `,
      {
        language: 'python',
        name: 'long-task'
      }
    );

    const processId = result.processId;
    console.log(`Process started: ${processId}`);
    console.log(`Status: ${result.status}`);

    await sandbox.kill();
    ```
  </Tab>
</Tabs>

## Checking Process Status

Check the status of background processes:

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    from hopx_ai import Sandbox
    import time

    sandbox = Sandbox.create(template="code-interpreter")

    # Start background task
    result = sandbox.run_code_background(
        code='import time; time.sleep(30); print("Done")',
        language='python',
        name='check-status-demo'
    )

    process_id = result['process_id']

    # Check status periodically
    for i in range(5):
        processes = sandbox.list_processes()
        for proc in processes:
            if proc['process_id'] == process_id:
                print(f"Status: {proc['status']}")
                if proc['status'] == 'completed':
                    print(f"Output: {proc.get('stdout', '')}")
                    break
        time.sleep(2)

    sandbox.kill()
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    import { Sandbox } from '@hopx-ai/sdk';

    const sandbox = await Sandbox.create({ template: 'code-interpreter' });

    // Start background task
    const result = await sandbox.runCodeBackground(
      'import time; time.sleep(30); print("Done")',
      {
        language: 'python',
        name: 'check-status-demo'
      }
    );

    const processId = result.processId;

    // Check status periodically
    for (let i = 0; i < 5; i++) {
      const processes = await sandbox.listProcesses();
      const proc = processes.find(p => p.processId === processId);
      
      if (proc) {
        console.log(`Status: ${proc.status}`);
        if (proc.status === 'completed') {
          console.log(`Output: ${proc.stdout || ''}`);
          break;
        }
      }
      
      await new Promise(resolve => setTimeout(resolve, 2000));
    }

    await sandbox.kill();
    ```
  </Tab>
</Tabs>

## Process Naming

Name your processes for easier identification:

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    from hopx_ai import Sandbox

    sandbox = Sandbox.create(template="code-interpreter")

    # Start multiple named processes
    proc1 = sandbox.run_code_background(
        code='import time; time.sleep(60)',
        language='python',
        name='data-processing'
    )

    proc2 = sandbox.run_code_background(
        code='import time; time.sleep(60)',
        language='python',
        name='ml-training'
    )

    # List processes by name
    processes = sandbox.list_processes()
    for proc in processes:
        print(f"{proc.get('name', 'unnamed')}: {proc['status']}")

    sandbox.kill()
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    import { Sandbox } from '@hopx-ai/sdk';

    const sandbox = await Sandbox.create({ template: 'code-interpreter' });

    // Start multiple named processes
    const proc1 = await sandbox.runCodeBackground(
      'import time; time.sleep(60)',
      {
        language: 'python',
        name: 'data-processing'
      }
    );

    const proc2 = await sandbox.runCodeBackground(
      'import time; time.sleep(60)',
      {
        language: 'python',
        name: 'ml-training'
      }
    );

    // List processes by name
    const processes = await sandbox.listProcesses();
    for (const proc of processes) {
      console.log(`${proc.name || 'unnamed'}: ${proc.status}`);
    }

    await sandbox.kill();
    ```
  </Tab>
</Tabs>

## Environment Variables

Pass environment variables to background execution:

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    from hopx_ai import Sandbox

    sandbox = Sandbox.create(template="code-interpreter")

    # Start background task with environment variables
    result = sandbox.run_code_background(
        code='''
    import os
    import time

    api_key = os.getenv("API_KEY")
    print(f"Using API key: {api_key[:10]}...")
    time.sleep(30)
    print("Task completed")
    ''',
        language='python',
        env={
            "API_KEY": "sk-123456",
            "DEBUG": "true"
        },
        name='env-demo'
    )

    print(f"Process ID: {result['process_id']}")

    sandbox.kill()
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    import { Sandbox } from '@hopx-ai/sdk';

    const sandbox = await Sandbox.create({ template: 'code-interpreter' });

    // Start background task with environment variables
    const result = await sandbox.runCodeBackground(
      `
    import os
    import time

    api_key = os.getenv("API_KEY")
    print(f"Using API key: {api_key[:10]}...")
    time.sleep(30)
    print("Task completed")
    `,
      {
        language: 'python',
        env: {
          API_KEY: 'sk-123456',
          DEBUG: 'true'
        },
        name: 'env-demo'
      }
    );

    console.log(`Process ID: ${result.processId}`);

    await sandbox.kill();
    ```
  </Tab>
</Tabs>

## Timeout Configuration

Set timeout for background execution:

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    from hopx_ai import Sandbox

    sandbox = Sandbox.create(template="code-interpreter")

    # Start background task with 10 minute timeout
    result = sandbox.run_code_background(
        code='import time; time.sleep(300)',
        language='python',
        timeout=600,  # 10 minutes
        name='long-task'
    )

    print(f"Process started with {result.get('timeout', 'default')}s timeout")

    sandbox.kill()
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    import { Sandbox } from '@hopx-ai/sdk';

    const sandbox = await Sandbox.create({ template: 'code-interpreter' });

    // Start background task with 10 minute timeout
    const result = await sandbox.runCodeBackground(
      'import time; time.sleep(300)',
      {
        language: 'python',
        timeout: 600,  // 10 minutes
        name: 'long-task'
      }
    );

    console.log(`Process started with ${result.timeout || 'default'}s timeout`);

    await sandbox.kill();
    ```
  </Tab>
</Tabs>

## Complete Example

Here's a complete example showing background execution workflow:

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    from hopx_ai import Sandbox
    import time

    sandbox = Sandbox.create(template="code-interpreter")

    # Start background task
    result = sandbox.run_code_background(
        code='''
    import time
    import random

    for i in range(20):
        value = random.randint(1, 100)
        print(f"Step {i+1}: Generated {value}")
        time.sleep(1)
    print("All done!")
    ''',
        language='python',
        timeout=300,
        name='random-generator',
        env={"SEED": "42"}
    )

    process_id = result['process_id']
    print(f"✅ Background task started: {process_id}")

    # Monitor progress
    while True:
        processes = sandbox.list_processes()
        proc = next((p for p in processes if p['process_id'] == process_id), None)
        
        if not proc:
            print("Process not found")
            break
        
        status = proc['status']
        print(f"Status: {status}")
        
        if status == 'completed':
            print(f"✅ Task completed!")
            print(f"Output:\n{proc.get('stdout', '')}")
            break
        elif status == 'failed':
            print(f"❌ Task failed!")
            print(f"Error: {proc.get('stderr', '')}")
            break
        
        time.sleep(2)

    sandbox.kill()
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    import { Sandbox } from '@hopx-ai/sdk';

    const sandbox = await Sandbox.create({ template: 'code-interpreter' });

    // Start background task
    const result = await sandbox.runCodeBackground(
      `
    import time
    import random

    for i in range(20):
        value = random.randint(1, 100)
        print(f"Step {i+1}: Generated {value}")
        time.sleep(1)
    print("All done!")
    `,
      {
        language: 'python',
        timeout: 300,
        name: 'random-generator',
        env: { SEED: '42' }
      }
    );

    const processId = result.processId;
    console.log(`✅ Background task started: ${processId}`);

    // Monitor progress
    while (true) {
      const processes = await sandbox.listProcesses();
      const proc = processes.find(p => p.processId === processId);
      
      if (!proc) {
        console.log('Process not found');
        break;
      }
      
      const status = proc.status;
      console.log(`Status: ${status}`);
      
      if (status === 'completed') {
        console.log('✅ Task completed!');
        console.log(`Output:\n${proc.stdout || ''}`);
        break;
      } else if (status === 'failed') {
        console.log('❌ Task failed!');
        console.log(`Error: ${proc.stderr || ''}`);
        break;
      }
      
      await new Promise(resolve => setTimeout(resolve, 2000));
    }

    await sandbox.kill();
    ```
  </Tab>
</Tabs>

## Best Practices

<Steps>
  <Step title="1. Use Descriptive Names">
    Always name your background processes for easier identification when listing and managing them.
  </Step>

  <Step title="2. Set Appropriate Timeouts">
    Set timeouts based on expected execution time. Default is 5 minutes, but you can extend for longer tasks.
  </Step>

  <Step title="3. Monitor Status Regularly">
    Check process status periodically to track progress and handle completion or failures.
  </Step>

  <Step title="4. Clean Up Completed Processes">
    Remove completed processes to keep your process list manageable. Use [Process Management](/core-concepts/code-execution/process-management) for cleanup.
  </Step>

  <Step title="5. Handle Failures">
    Always check for failed status and handle errors appropriately. Access `stderr` for error details.
  </Step>
</Steps>

## Implementation

* **SDK**: [sandbox.run\_code\_background()](/sdk/python/sandbox#run_code_background) - Python SDK method
* **[CLI](/cli/introduction)** - Command-line interface
* **API**: [POST /execute/background](/api/vm-agent/execute-background) - VM Agent API endpoint

## Related

* **[Process Management](/core-concepts/code-execution/process-management)** - Monitor and manage background processes
* **[Synchronous Execution](/core-concepts/code-execution/synchronous)** - Execute code synchronously
* **[Streaming Execution](/core-concepts/code-execution/streaming)** - Real-time output streaming
* **[Async Execution with Webhooks](/core-concepts/code-execution/async-webhooks)** - Very long-running tasks

## Next Steps

* Learn about [Process Management](/core-concepts/code-execution/process-management) to monitor and control background processes
* Explore [Async Webhooks](/core-concepts/code-execution/async-webhooks) for very long-running tasks (>30 minutes)
* Review [Synchronous Execution](/core-concepts/code-execution/synchronous) for immediate results
