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

# Tiempo de espera por inactividad

export const SandboxConfigHint = () => {
  if (typeof document === "undefined") {
    return null;
  } else {
    return <Note>Before running the example code in this document, please ensure you have properly configured environment variables. For details, please refer to <a href="/docs/es/guides/sandbox-your-first-agent-sandbox#configure-environment-variables">Configure Environment Variables</a>.</Note>;
  }
};

Puedes configurar un **tiempo de espera por inactividad** para que tus sandboxes se detengan o pausen automáticamente cuando no se detecten conexiones activas. Esto ayuda a reducir costos al garantizar que los sandboxes no utilizados no se ejecuten indefinidamente.

<SandboxConfigHint />

<Note>
  El tiempo de espera por inactividad se configura mediante el campo `metadata` al crear un sandbox. La clave es `idle_timeout` y el valor es el número de segundos (como una cadena).
</Note>

## Uso básico

Pasa la clave `idle_timeout` en el objeto `metadata` al crear un sandbox. El valor es la duración del tiempo de espera por inactividad en **segundos** (como una cadena). Cuando ningún cliente esté conectado al sandbox durante la duración especificada, el sandbox se terminará o pausará automáticamente.

<CodeGroup>
  ```js JavaScript & TypeScript icon="js" theme={"system"}
  import { Sandbox } from 'novita-sandbox/code-interpreter'

  // Create a sandbox that will be automatically killed after 60 seconds of inactivity.
  const sandbox = await Sandbox.create({
    metadata: {
      idle_timeout: '60',
    },
  })

  // The sandbox is running...
  // After 60 seconds with no active connections, it will be killed automatically.
  ```

  ```python Python icon="python" theme={"system"}
  from novita_sandbox.code_interpreter import Sandbox

  # Create a sandbox that will be automatically killed after 60 seconds of inactivity.
  sandbox = Sandbox.create(
      metadata={
          "idle_timeout": "60",
      },
  )

  # The sandbox is running...
  # After 60 seconds with no active connections, it will be killed automatically.
  ```
</CodeGroup>

## Cómo funciona el tiempo de espera por inactividad

La función de tiempo de espera por inactividad supervisa las conexiones activas a tu sandbox:

1. **Cuando no hay conexiones activas**: la hora de finalización del sandbox se establece en `current_time + idle_timeout_seconds`.
2. **Cuando una conexión vuelve a estar activa**: la hora de finalización del sandbox se restaura a la vida útil máxima original del sandbox.
3. **Cuando transcurre el tiempo de espera por inactividad sin ninguna reconexión**: el sandbox se termina (o se pausa si `autoPause` está habilitado).

Esto significa que un sandbox no se detendrá mientras haya al menos un cliente activo conectado a él (por ejemplo, mediante `Sandbox.connect()` o conexiones WebSocket/HTTP abiertas).

## Pausar en lugar de terminar

De forma predeterminada, un sandbox inactivo se **termina** cuando vence el tiempo de espera por inactividad. Si quieres que el sandbox se **pause** en su lugar para poder reanudarlo más tarde, habilita la opción `autoPause`:

<CodeGroup>
  ```js JavaScript & TypeScript icon="js" theme={"system"}
  import { Sandbox } from 'novita-sandbox/code-interpreter'

  // Create a sandbox that will be paused (instead of killed) after 60 seconds of inactivity.
  const sandbox = await Sandbox.create({
    metadata: {
      idle_timeout: '60',
    },
    autoPause: true,
  })

  // After 60 seconds of inactivity, the sandbox will be paused.
  // You can resume it later with Sandbox.connect().
  ```

  ```python Python icon="python" theme={"system"}
  from novita_sandbox.code_interpreter import Sandbox

  # Create a sandbox that will be paused (instead of killed) after 60 seconds of inactivity.
  sandbox = Sandbox.create(
      metadata={
          "idle_timeout": "60",
      },
      auto_pause=True,
  )

  # After 60 seconds of inactivity, the sandbox will be paused.
  # You can resume it later with Sandbox.connect().
  ```
</CodeGroup>

<Note>
  Cuando `autoPause` está habilitado, el estado del sandbox cambia a `paused` al producirse el tiempo de espera por inactividad. Puedes [conectarte](/docs/es/guides/sandbox-connect) a él más tarde para reanudar la ejecución.
</Note>

## Combinar con otros metadatos

La clave de metadatos `idle_timeout` puede combinarse con otras claves de metadatos que ya utilices:

<CodeGroup>
  ```js JavaScript & TypeScript icon="js" theme={"system"}
  import { Sandbox } from 'novita-sandbox/code-interpreter'

  const sandbox = await Sandbox.create({
    metadata: {
      idle_timeout: '120',
      env: 'production',
      userId: 'user-123',
    },
  })

  console.log('Sandbox ID:', sandbox.sandboxId)
  ```

  ```python Python icon="python" theme={"system"}
  from novita_sandbox.code_interpreter import Sandbox

  sandbox = Sandbox.create(
      metadata={
          "idle_timeout": "120",
          "env": "production",
          "user_id": "user-123",
      },
  )

  print("Sandbox ID:", sandbox.sandbox_id)
  ```
</CodeGroup>

## Restricciones de tiempo de espera

| Restricción        | Valor                 | Descripción                                                                                                                |
| ------------------ | --------------------- | -------------------------------------------------------------------------------------------------------------------------- |
| **Mínimo**         | 30 segundos           | Los valores inferiores a 30 segundos se tratan como "inactividad deshabilitada" para evitar ciclos rápidos de inicio/stop. |
| **Predeterminado** | Deshabilitado (0)     | Si no se especifica `idle_timeout`, la función se deshabilita y el sandbox se ejecuta hasta alcanzar su vida útil máxima.  |
| **Máximo**         | Vida útil del sandbox | El tiempo de espera por inactividad no puede superar el `timeout` configurado del sandbox (vida útil máxima).              |

<Warning>
  Si estableces `idle_timeout` en un valor inferior al umbral mínimo (30 segundos), la función de tiempo de espera por inactividad se **deshabilitará silenciosamente** para ese sandbox. El sandbox se ejecutará hasta que expire su vida útil máxima.
</Warning>

## Deshabilitar el tiempo de espera por inactividad

Para deshabilitar explícitamente el tiempo de espera por inactividad de un sandbox, simplemente omite la clave `idle_timeout` de los metadatos, o establécela en `"0"`:

<CodeGroup>
  ```js JavaScript & TypeScript icon="js" theme={"system"}
  import { Sandbox } from 'novita-sandbox/code-interpreter'

  // No idle timeout — sandbox runs until its maximum lifetime.
  const sandbox = await Sandbox.create({
    metadata: {
      idle_timeout: '0',
    },
  })

  // Alternatively, omit idle_timeout entirely:
  const sandbox2 = await Sandbox.create()
  ```

  ```python Python icon="python" theme={"system"}
  from novita_sandbox.code_interpreter import Sandbox

  # No idle timeout — sandbox runs until its maximum lifetime.
  sandbox = Sandbox.create(
      metadata={
          "idle_timeout": "0",
      },
  )

  # Alternatively, omit idle_timeout entirely:
  sandbox2 = Sandbox.create()
  ```
</CodeGroup>

## Casos de uso comunes

### Tareas de ejecución de corta duración

Usa un tiempo de espera por inactividad corto para sandboxes que ejecutan tareas puntuales y no necesitan persistir después de que el cliente se desconecta:

<CodeGroup>
  ```js JavaScript & TypeScript icon="js" theme={"system"}
  import { Sandbox } from 'novita-sandbox/code-interpreter'

  const sandbox = await Sandbox.create({
    metadata: { idle_timeout: '60' },
  })

  // Execute code and get results...
  const result = await sandbox.runCode('print("Hello!")')

  // Disconnect — sandbox will be killed after 60 seconds of inactivity.
  await sandbox.kill()
  ```

  ```python Python icon="python" theme={"system"}
  from novita_sandbox.code_interpreter import Sandbox

  sandbox = Sandbox.create(
      metadata={"idle_timeout": "60"},
  )

  # Execute code and get results...
  result = sandbox.run_code('print("Hello!")')

  # Disconnect — sandbox will be killed after 60 seconds of inactivity.
  sandbox.kill()
  ```
</CodeGroup>

### Sesiones interactivas de larga duración

Usa un tiempo de espera por inactividad más largo para sandboxes utilizados en sesiones interactivas en las que los usuarios pueden ausentarse temporalmente:

<CodeGroup>
  ```js JavaScript & TypeScript icon="js" theme={"system"}
  import { Sandbox } from 'novita-sandbox/code-interpreter'

  const sandbox = await Sandbox.create({
    metadata: { idle_timeout: '600' }, // 10 minutes
    autoPause: true,
  })

  // The sandbox will pause after 10 minutes of inactivity,
  // and can be resumed when the user returns.
  ```

  ```python Python icon="python" theme={"system"}
  from novita_sandbox.code_interpreter import Sandbox

  sandbox = Sandbox.create(
      metadata={"idle_timeout": "600"},  # 10 minutes
      auto_pause=True,
  )

  # The sandbox will pause after 10 minutes of inactivity,
  # and can be resumed when the user returns.
  ```
</CodeGroup>
