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

# Timeout

> Set and extend sandbox timeouts to control when sandboxes are automatically destroyed. Configure auto-shutdown timers to manage resources, extend timeouts for long-running tasks, and check remaining time. Essential for cost management and resource optimization. Includes Python and JavaScript SDK examples and REST API endpoints.

Sandboxes can be configured with automatic timeout values that determine when they are automatically destroyed. This helps manage resources and costs while ensuring sandboxes don't run indefinitely.

## Overview

Timeout management allows you to:

* Set an initial timeout when creating a sandbox
* Extend the timeout for running sandboxes
* Automatically destroy sandboxes after the timeout expires

<Note>
  When a timeout expires, the sandbox is automatically destroyed. All data in the sandbox is lost. Make sure to save important data before the timeout expires.
</Note>

## Setting Timeout on Creation

Set a timeout when creating a sandbox:

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

    # Create sandbox with 1 hour timeout
    sandbox = Sandbox.create(
        template="code-interpreter",
        timeout_seconds=3600  # 1 hour in seconds
    )

    info = sandbox.get_info()
    if info.expires_at:
        print(f"Sandbox expires at: {info.expires_at}")
    ```

    **Expected Output:**

    ```
    Sandbox expires at: 2025-01-27T11:00:00Z
    ```
  </Tab>

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

    // Create sandbox with 1 hour timeout
    const sandbox = await Sandbox.create({
      template: 'code-interpreter',
      timeoutSeconds: 3600  // 1 hour in seconds
    });

    const info = await sandbox.getInfo();
    if (info.expiresAt) {
      console.log(`Sandbox expires at: ${info.expiresAt}`);
    }
    ```

    **Expected Output:**

    ```
    Sandbox expires at: 2025-01-27T11:00:00Z
    ```
  </Tab>
</Tabs>

## Extending Timeout

Extend the timeout for an existing sandbox:

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

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

    # Extend timeout to 2 hours from now
    sandbox.set_timeout(7200)  # 2 hours in seconds

    # Verify new timeout
    info = sandbox.get_info()
    if info.expires_at:
        print(f"New expiration: {info.expires_at}")
    ```

    **Expected Output:**

    ```
    New expiration: 2025-01-27T12:00:00Z
    ```
  </Tab>

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

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

    // Extend timeout to 2 hours from now
    await sandbox.setTimeout(7200);  // 2 hours in seconds

    // Verify new timeout
    const info = await sandbox.getInfo();
    if (info.expiresAt) {
      console.log(`New expiration: ${info.expiresAt}`);
    }
    ```

    **Expected Output:**

    ```
    New expiration: 2025-01-27T12:00:00Z
    ```
  </Tab>
</Tabs>

<Warning>
  The `set_timeout()` method sets a new timeout duration **from the current time**, not from the original expiration. Each call resets the timer.
</Warning>

## Common Timeout Values

Use these common timeout values:

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

    # Quick tasks (5 minutes)
    sandbox = Sandbox.create(
        template="code-interpreter",
        timeout_seconds=300
    )

    # Standard tasks (30 minutes)
    sandbox = Sandbox.create(
        template="code-interpreter",
        timeout_seconds=1800
    )

    # Long-running tasks (1 hour)
    sandbox = Sandbox.create(
        template="code-interpreter",
        timeout_seconds=3600
    )

    # Extended tasks (4 hours)
    sandbox = Sandbox.create(
        template="code-interpreter",
        timeout_seconds=14400
    )
    ```
  </Tab>

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

    // Quick tasks (5 minutes)
    const sandbox1 = await Sandbox.create({
      template: 'code-interpreter',
      timeoutSeconds: 300
    });

    // Standard tasks (30 minutes)
    const sandbox2 = await Sandbox.create({
      template: 'code-interpreter',
      timeoutSeconds: 1800
    });

    // Long-running tasks (1 hour)
    const sandbox3 = await Sandbox.create({
      template: 'code-interpreter',
      timeoutSeconds: 3600
    });

    // Extended tasks (4 hours)
    const sandbox4 = await Sandbox.create({
      template: 'code-interpreter',
      timeoutSeconds: 14400
    });
    ```
  </Tab>
</Tabs>

## Checking Expiration

Check when a sandbox will expire:

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

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

    info = sandbox.get_info()
    if info.expires_at:
        expires = datetime.fromisoformat(info.expires_at.replace('Z', '+00:00'))
        now = datetime.now(expires.tzinfo)
        remaining = expires - now
        
        print(f"Expires at: {info.expires_at}")
        print(f"Time remaining: {remaining.total_seconds() / 60:.1f} minutes")
    ```

    **Expected Output:**

    ```
    Expires at: 2025-01-27T11:00:00Z
    Time remaining: 55.2 minutes
    ```
  </Tab>

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

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

    const info = await sandbox.getInfo();
    if (info.expiresAt) {
      const expires = new Date(info.expiresAt);
      const now = new Date();
      const remaining = (expires - now) / 1000 / 60;  // minutes
      
      console.log(`Expires at: ${info.expiresAt}`);
      console.log(`Time remaining: ${remaining.toFixed(1)} minutes`);
    }
    ```

    **Expected Output:**

    ```
    Expires at: 2025-01-27T11:00:00Z
    Time remaining: 55.2 minutes
    ```
  </Tab>
</Tabs>

## Extending Before Expiration

Extend timeout before it expires to prevent automatic destruction:

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

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

    # Check remaining time
    info = sandbox.get_info()
    if info.expires_at:
        expires = datetime.fromisoformat(info.expires_at.replace('Z', '+00:00'))
        now = datetime.now(expires.tzinfo)
        remaining_minutes = (expires - now).total_seconds() / 60
        
        # Extend if less than 10 minutes remaining
        if remaining_minutes < 10:
            print("Extending timeout...")
            sandbox.set_timeout(3600)  # Extend by 1 hour
            print("Timeout extended")
    ```

    **Expected Output:**

    ```
    Extending timeout...
    Timeout extended
    ```
  </Tab>

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

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

    // Check remaining time
    let info = await sandbox.getInfo();
    if (info.expiresAt) {
      const expires = new Date(info.expiresAt);
      const now = new Date();
      const remainingMinutes = (expires - now) / 1000 / 60;
      
      // Extend if less than 10 minutes remaining
      if (remainingMinutes < 10) {
        console.log('Extending timeout...');
        await sandbox.setTimeout(3600);  // Extend by 1 hour
        console.log('Timeout extended');
      }
    }
    ```

    **Expected Output:**

    ```
    Extending timeout...
    Timeout extended
    ```
  </Tab>
</Tabs>

## No Timeout (Indefinite)

Create a sandbox without a timeout (runs until manually killed):

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

    # Create without timeout (or set to None)
    sandbox = Sandbox.create(
        template="code-interpreter"
        # timeout_seconds not specified = no timeout
    )

    info = sandbox.get_info()
    if info.expires_at:
        print(f"Expires: {info.expires_at}")
    else:
        print("No timeout - runs indefinitely")
    ```

    **Expected Output:**

    ```
    No timeout - runs indefinitely
    ```
  </Tab>

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

    // Create without timeout
    const sandbox = await Sandbox.create({
      template: 'code-interpreter'
      // timeoutSeconds not specified = no timeout
    });

    const info = await sandbox.getInfo();
    if (info.expiresAt) {
      console.log(`Expires: ${info.expiresAt}`);
    } else {
      console.log('No timeout - runs indefinitely');
    }
    ```

    **Expected Output:**

    ```
    No timeout - runs indefinitely
    ```
  </Tab>
</Tabs>

## Complete Example

Here's a complete example showing timeout management:

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

    # Create with initial timeout
    sandbox = Sandbox.create(
        template="code-interpreter",
        timeout_seconds=1800  # 30 minutes
    )

    info = sandbox.get_info()
    print(f"Initial timeout: {info.expires_at}")

    # Do some work
    sandbox.run_code('print("Working...")', language="python")

    # Extend timeout before expiration
    sandbox.set_timeout(3600)  # Extend to 1 hour from now

    info = sandbox.get_info()
    print(f"Extended timeout: {info.expires_at}")

    # Check remaining time
    if info.expires_at:
        expires = datetime.fromisoformat(info.expires_at.replace('Z', '+00:00'))
        remaining = (expires - datetime.now(expires.tzinfo)).total_seconds()
        print(f"Time remaining: {remaining / 60:.1f} minutes")
    ```

    **Expected Output:**

    ```
    Initial timeout: 2025-01-27T10:30:00Z
    Working...
    Extended timeout: 2025-01-27T11:30:00Z
    Time remaining: 60.0 minutes
    ```
  </Tab>

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

    // Create with initial timeout
    const sandbox = await Sandbox.create({
      template: 'code-interpreter',
      timeoutSeconds: 1800  // 30 minutes
    });

    let info = await sandbox.getInfo();
    console.log(`Initial timeout: ${info.expiresAt}`);

    // Do some work
    await sandbox.runCode('print("Working...")', { language: 'python' });

    // Extend timeout before expiration
    await sandbox.setTimeout(3600);  // Extend to 1 hour from now

    info = await sandbox.getInfo();
    console.log(`Extended timeout: ${info.expiresAt}`);

    // Check remaining time
    if (info.expiresAt) {
      const expires = new Date(info.expiresAt);
      const remaining = (expires - new Date()) / 1000 / 60;
      console.log(`Time remaining: ${remaining.toFixed(1)} minutes`);
    }
    ```

    **Expected Output:**

    ```
    Initial timeout: 2025-01-27T10:30:00Z
    Working...
    Extended timeout: 2025-01-27T11:30:00Z
    Time remaining: 60.0 minutes
    ```
  </Tab>
</Tabs>

## API Direct Access

You can also manage timeouts using direct API calls:

```bash theme={null}
# Set timeout when creating
curl -X POST https://api.hopx.dev/v1/sandboxes \
  -H "Authorization: Bearer your-API key" \
  -H "Content-Type: application/json" \
  -d '{
    "template_name": "code-interpreter",
    "timeout_seconds": 3600
  }'

# Update timeout for existing sandbox
curl -X PUT https://api.hopx.dev/v1/sandboxes/{sandbox_id}/timeout \
  -H "Authorization: Bearer your-API key" \
  -H "Content-Type: application/json" \
  -d '{
    "timeout_seconds": 7200
  }'
```

## Best Practices

<Steps>
  <Step title="1. Set Appropriate Initial Timeouts">
    Set timeouts based on expected task duration. For quick scripts, use shorter timeouts. For long-running tasks, set longer timeouts.
  </Step>

  <Step title="2. Monitor Remaining Time">
    Check expiration time regularly for long-running sandboxes to avoid unexpected destruction.
  </Step>

  <Step title="3. Extend Before Expiration">
    Extend timeouts before they expire to prevent data loss. Consider setting up monitoring to alert when time is running low.
  </Step>

  <Step title="4. Save Important Data">
    Always save important data before timeout expires. Consider downloading files or storing results externally.
  </Step>

  <Step title="5. Use No Timeout for Development">
    For development and debugging, consider creating sandboxes without timeouts, but remember to clean them up manually.
  </Step>
</Steps>

## Timeout vs Manual Cleanup

<CardGroup cols={2}>
  <Card title="Automatic Timeout" icon="clock">
    Set `timeout_seconds` when creating or use `set_timeout()` to automatically destroy sandboxes after a specified duration. Best for production workloads.
  </Card>

  <Card title="Manual Cleanup" icon="trash-2">
    Call `sandbox.kill()` when done. Best for development or when you need precise control over when sandboxes are destroyed.
  </Card>
</CardGroup>

## Implementation

* **SDK**: [sandbox.set\_timeout()](/sdk/python/sandbox#set_timeout) - Python SDK method
* **[CLI](/cli/introduction)** - Command-line interface
* **API**: [PUT /v1/sandboxes/:id/timeout](/api/control-plane/set-timeout) - Control Plane API endpoint

## Related

* **[Creating Sandboxes](/core-concepts/sandboxes/creating)** - Set timeout on creation
* **[Managing Sandbox State](/core-concepts/sandboxes/managing-state)** - Control sandbox lifecycle
* **[Connecting to Sandboxes](/core-concepts/sandboxes/connecting)** - Connect to existing sandboxes

## Next Steps

* Learn about [Creating Sandboxes](/core-concepts/sandboxes/creating) with timeout configuration
* Explore [Managing State](/core-concepts/sandboxes/managing-state) for lifecycle control
* Review [Listing Sandboxes](/core-concepts/sandboxes/listing) to monitor sandbox status
