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

# 超时处理

每个 Sandbox 都有一个由 `timeout` 设置控制的**最长存活时间**。超时到期后,Sandbox 会被停止。默认情况下,新建的 Sandbox 存活 **5 分钟**。

<Note>
  **Timeout 与 Idle timeout —— 不要混淆:**

  * **Timeout** 是 Sandbox 的最长存活时间。它从创建时开始倒计时,与是否有活动无关,到期后必定生效。
  * **Idle timeout** 仅在没有客户端连接持续达到配置时长时才会触发。
</Note>

## 创建带超时的 Sandbox

<CodeGroup>
  ```python Python theme={null}
  from ppio_sandbox import PPIO

  ppio = PPIO()

  sandbox = ppio.sandbox.create(timeout=60)

  sandbox.kill()
  ```

  ```typescript JavaScript & TypeScript theme={null}
  import { PPIO } from 'ppio-sandbox'

  const ppio = new PPIO()

  const sandbox = await ppio.sandbox.create({ timeoutMs: 60_000 })

  await sandbox.kill()
  ```

  ```bash CLI theme={null}
  # 创建 timeout 为 60 秒的 Sandbox（分离模式），返回 Sandbox ID
  ppio sandbox create base --timeout 60s -d

  # 终止 Sandbox
  ppio sandbox kill <sandbox_id>
  ```
</CodeGroup>

## 更新超时时间

你可以使用 `setTimeout` / `set_timeout` 重置 Sandbox 还应继续存活多长时间。

<CodeGroup>
  ```python Python theme={null}
  from ppio_sandbox import PPIO

  ppio = PPIO()

  sandbox = ppio.sandbox.create(timeout=60)

  sandbox.set_timeout(300)
  sandbox.kill()
  ```

  ```typescript JavaScript & TypeScript theme={null}
  import { PPIO } from 'ppio-sandbox'

  const ppio = new PPIO()

  const sandbox = await ppio.sandbox.create({ timeoutMs: 60_000 })

  await sandbox.setTimeout(300_000)
  await sandbox.kill()
  ```

  ```bash CLI theme={null}
  # 将 Sandbox 的 timeout 重置为 5 分钟
  ppio sandbox set-timeout <sandbox_id> 5m
  ```
</CodeGroup>

## 生命周期行为

你可以将 `timeout` 与 `lifecycle` 结合使用,选择超时到期时是终止还是暂停 Sandbox。

<CodeGroup>
  ```python Python theme={null}
  from ppio_sandbox import PPIO

  ppio = PPIO()

  sandbox = ppio.sandbox.create(
      timeout=300,
      lifecycle={
          'on_timeout': 'pause',
          'auto_resume': True,
      },
  )
  ```

  ```typescript JavaScript & TypeScript theme={null}
  import { PPIO } from 'ppio-sandbox'

  const ppio = new PPIO()

  const sandbox = await ppio.sandbox.create({
    timeoutMs: 300_000,
    lifecycle: {
      onTimeout: 'pause',
      autoResume: true,
    },
  })
  ```

  ```bash CLI theme={null}
  # 超时到期时暂停 Sandbox 而不是终止，并允许自动恢复
  ppio sandbox create base --timeout 5m --on-timeout pause --auto-resume -d
  ```
</CodeGroup>

如果不传 `lifecycle`,超时到期时 Sandbox 会被终止。
