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

# 闲时释放

export const SandboxBetaVersionWarning = () => {
  if (typeof document === "undefined") {
    return null;
  } else {
    return <Warning>注意以下功能需要 <Link href="/sandbox/sandbox-sdk-and-cli#安装-beta-版-sdk" target="self">安装 Beta SDK & CLI</Link> 才能使用。另外 Beta 版功能在合并到稳定版前，可能会经历多次迭代，因此可能存在不稳定性。如果您在使用过程中遇到任何问题，欢迎 <Link href="https://ppio.com/contact" target="_blank">联系我们</Link>。</Warning>;
  }
};

<SandboxBetaVersionWarning />

我们可以为每个沙箱设置一个 timeout（参考 [生命周期管理](/sandbox/sandbox)），当沙箱运行时间达到 timeout 时，沙箱将自动释放。但是有些场景下，我们无法明确沙箱预计运行的时间，但我们希望沙箱在不使用时，能够自动释放，以节省成本。此时，您可以使用 **“闲时释放”** 功能。

在创建沙箱时，我们可以在 metadata 中设置 idle\_timeout 参数（单位：秒，最小为 60）来启用 **“闲时释放”** 功能。启用后，当系统识别到沙箱在指定的时间范围内没有任何操作时（执行命令、运行代码、操作文件等），系统将会释放该沙箱实例，否则沙箱会持续运行，直到达到系统限制沙箱运行的最大时间（当前默认是 3600s）。

请参考如下示例：

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

  const sandbox = await Sandbox.create(
      {
          metadata: { "idle_timeout": "60" }
      }
  );
  console.log('Sandbox created', sandbox.sandboxId)

  const result = await sandbox.commands.run('ls -al')
  console.log('Command result', result)

  await new Promise(resolve => setTimeout(resolve, 90000));

  const isRunning = await sandbox.isRunning()
  console.log('Sandbox is running', isRunning)

  await sandbox.kill()
  ```

  ```python Python icon="python" theme={null}
  from ppio_sandbox.core import Sandbox
  import time

  sandbox = Sandbox.create(
      metadata={"idle_timeout": "60"}  # Minimum time is 60s,You can customize it
  )
  print('Sandbox created', sandbox.sandbox_id)

  result = sandbox.commands.run('ls -al')
  print('Command result', result)

  print('Waiting for 10 seconds...')
  time.sleep(90)

  is_running = sandbox.is_running()
  print('Sandbox is running', is_running)

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