每个沙箱都有一个 timeout(“超时时间”)配置,当沙箱的运行时间超过该配置值时,沙箱将自动关闭并释放。

您可以参考如下方式在启动的时候显式指定 timeout 的配置值,如果未指定,则默认值为 5 分钟。当前允许设置的最大值为 1 小时。

import { Sandbox } from '@e2b/code-interpreter'

// 创建一个沙箱,并保持运行 60 秒。
const sandbox = await Sandbox.create({
  timeoutMs: 60_000, // 单位为毫秒。
})

更新沙箱超时时间

您可以参考如下示例来在沙箱运行过程中更新其 timeout 配置值,更新后,沙箱的 timeout 将重置为最新值(从更新生效后的时间点开始计时)。

请注意,当前沙箱的最大存活时间为 1 小时,不能通过本方法让沙箱运行更长的时间。

import { Sandbox } from '@e2b/code-interpreter'

// 创建一个沙箱,并保持运行 60 秒。
const sandbox = await Sandbox.create({ timeoutMs: 60_000 })

// 更改沙箱超时时间为 30 秒(从方法执行后开始计时)。
await sandbox.setTimeout(30_000)

获取沙箱信息

您可以通过如下方法来获取沙箱信息,包括沙箱 ID、沙箱模板 ID、沙箱元数据信息、开始时间和结束时间等。

import { Sandbox } from '@e2b/code-interpreter'

// 创建一个沙箱,并保持运行 60 秒。
const sandbox = await Sandbox.create({ timeoutMs: 60_000 })

// 获取沙箱信息。
const info = await sandbox.getInfo()

console.log(info)

// 输出结果示例:
// {
//   sandboxId: 'i2n8dnaa31gr4yo6ykf7r-1e67fa95',
//   templateId: 'uhop43uji8fr7qkfbmsp',
//   name: 'code-interpreter-v1',
//   metadata: {},
//   envdVersion: '0.2.0',
//   envdAccessToken: undefined,
//   startedAt: 2025-06-21T09:13:01.116Z,
//   endAt: 2025-06-21T09:14:01.116Z
// }

关闭沙箱

您可以通过调用 kill 方法在沙箱自动超时前的任意时刻关闭沙箱实例。

import { Sandbox } from '@e2b/code-interpreter'

// 创建一个沙箱,并保持运行 60 秒。
const sandbox = await Sandbox.create({ timeoutMs: 60_000 })

// 立即关闭沙箱。
await sandbox.kill()