全栈应用服务器

  • 全栈应用服务器 > 使用指南 > 沙箱服务概述 > 沙箱生命周期

    沙箱生命周期

    最近更新时间: 2026-02-12 11:21:56

    概述

    本文档涵盖了沙箱实例的管理,包括创建、超时配置、信息检索和关闭流程。

    默认行为

    默认行为: Sandbox 默认运行 5 分钟,但支持自定义超时设置。

    运行时间限制:

    • 单个沙箱最长运行时间默认为 1 小时
    • 如需更长的运行时间,可以联系我们申请调整

    使用超时创建 Sandbox

    import { Sandbox } from '@e2b/code-interpreter'
    
    // Create sandbox with and keep it running for 60 seconds.
    // Note: The units are milliseconds.
    async function main() {
      const sandbox = await Sandbox.create({
        timeoutMs: 60_000,
      })
      await sandbox.kill()
    }
    
    main()
    

    注意: JavaScript/TypeScript 使用毫秒作为单位。

    在运行时更改超时

    你可以在 sandbox 运行时重置其生命周期:

    import { Sandbox } from '@e2b/code-interpreter'
    
    async function main() {
      // Create sandbox with and keep it running for 60 seconds.
      const sandbox = await Sandbox.create({ timeoutMs: 60_000 })
    
      // Change the sandbox timeout to 30 seconds.
      // The new timeout will be 30 seconds from now.
      await sandbox.setTimeout(30_000)
    
      await sandbox.kill()
    }
    
    main()
    

    重要: 新的超时时间是从当前时刻开始计算的。

    获取 Sandbox 信息

    使用 getInfo()get_info() 方法可以访问 sandbox ID、模板、元数据和时间戳。

    import { Sandbox } from '@e2b/code-interpreter'
    
    async function main() {
      // Create sandbox with and keep it running for 60 seconds.
      const sandbox = await Sandbox.create({ timeoutMs: 60_000 })
    
      // Retrieve sandbox information.
      const info = await sandbox.getInfo()
    
      console.log(info)
    
      // {
      //   "sandboxId": "iiny0783cype8gmoawzmx-ce30bc46",
      //   "templateId": "rki5dems9wqfm4r03t7g",
      //   "name": "base",
      //   "metadata": {},
      //   "startedAt": "2025-03-24T15:37:58.076Z",
      //   "endAt": "2025-03-24T15:42:58.076Z"
      // }
    
      await sandbox.kill()
    }
    
    main()
    

    关闭 Sandbox

    kill() 方法可以立即终止 sandbox,无论剩余超时时间如何。

    import { Sandbox } from '@e2b/code-interpreter'
    
    async function main() {
      // Create sandbox with and keep it running for 60 seconds.
      const sandbox = await Sandbox.create({ timeoutMs: 60_000 })
    
      // Shutdown the sandbox immediately.
      await sandbox.kill()
    }
    
    main()
    

    使用场景

    支持交互式应用,根据用户活动延长 sandbox 持续时间,防止活动会话过早终止。

    以上内容是否对您有帮助?