您现在可以暂停沙箱并且在后续需要时恢复该沙箱,恢复后,沙箱的文件系统和内存状态,包括正在运行的进程、已加载的变量、数据等都将被恢复。在沙箱暂停期间,我们不会对沙箱的运行时间计费。

沙箱 ”暂停和恢复“ 功能目前处于 Beta 测试阶段,您需要安装 Beta 版本 SDK 来使用。

请注意:

  • 暂停沙箱所需的时间和沙箱的 RAM(内存)大小有关,每 1 GB RAM 需要约 4 秒;
  • 恢复沙箱需要约 1 秒;
  • 沙箱最多可以暂停 30 天。30 天后,数据将被删除,您将无法恢复沙箱。尝试恢复已删除或不存在的沙箱将导致 NotFoundError 错误(JavaScript SDK)或 NotFoundException 异常(Python SDK)。

暂停沙箱

当您暂停沙箱时,沙箱的文件系统和内存状态都将被保存。包括沙箱文件系统中的所有文件以及所有正在运行的进程、已加载的变量、数据等。

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

const sbx = await Sandbox.create()
console.log('Sandbox created', sbx.sandboxId)

// 暂停沙箱
// 建议您将沙箱 ID 保存到数据库中,以便稍后恢复沙箱。
const sandboxId = await sbx.pause()
console.log('Sandbox paused', sandboxId)

恢复沙箱

当您恢复沙箱时,沙箱在暂停前文件系统中的所有文件、所有正在运行的进程、已加载的变量、数据等将被恢复。

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

const sbx = await Sandbox.create()
console.log('Sandbox created', sbx.sandboxId)

// 暂停沙箱
// 建议您将沙箱 ID 保存到数据库中,以便稍后恢复沙箱。
const sandboxId = await sbx.pause()
console.log('Sandbox paused', sandboxId)

// 恢复沙箱
const sameSbx = await Sandbox.resume(sandboxId)
console.log('Sandbox resumed', sameSbx.sandboxId)

恢复时指定超时时间

当您恢复沙箱时,沙箱的 timeout 会重置为默认的 5 分钟。您可以参考如下方法来自定义 timeout 值。

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

const sbx = await Sandbox.resume(sandboxId, { timeoutMs: 60 * 1000 }) // 60 秒

列出暂停的沙箱

您可以参考如下方式列出所有被暂停的沙箱。详情请参考 沙箱列表

import { Sandbox, SandboxInfo } from '@e2b/code-interpreter'
// or import { Sandbox, SandboxInfo } from 'e2b'
// or import { Sandbox, SandboxInfo } from '@e2b/desktop'

// 过滤出所有被暂停的沙箱
const paginator = Sandbox.list({ query: { state: ['paused'] } })

// 分页获取所有被暂停的沙箱
const sandboxes: SandboxInfo[] = []
while (paginator.hasNext) {
  const items = await paginator.nextItems()
  sandboxes.push(...items)
}

console.log('all paused sandboxes', sandboxes)

删除暂停的沙箱

您可以通过在沙箱实例上调用 kill 方法来删除暂停的沙箱。

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

const sbx = await Sandbox.create()
console.log('Sandbox created', sbx.sandboxId)

// 暂停沙箱
const sandboxId = await sbx.pause()

// 删除被暂停的沙箱
await sbx.kill()

// 或者通过指定沙箱 ID 来删除被暂停的沙箱
// await Sandbox.kill(sandboxId)

网络连接

当您在沙箱内运行了服务并且暂停沙箱后,该服务将无法再从外部访问,所有客户端都将断开连接。在您恢复沙箱后,该服务可被再次访问,但您需要重新连接客户端。