跳转到主要内容
当您的沙箱实例当前不需要再使用,但后续需要随时能恢复使用时,您可以参考 文档 来主动暂停和恢复沙箱实例。 在某些情况下,您希望沙箱实例在 超时 后自动暂停,并且在您尝试操作沙箱实例(执行命令、运行代码、操作文件等)时,如果该沙箱实例已被暂停,则自动恢复该沙箱实例。此时,您可以使用 “自动暂停和恢复” 功能。

启用自动暂停功能

您可以在创建沙箱实例时设置 auto_pause 参数为true 来启用自动暂停功能,沙箱实例超时后会自动暂停,后续可被恢复。
注意:恢复后的沙箱实例仍会开启自动暂停功能,超时后会再次自动暂停。
import { Sandbox } from 'ppio-sandbox/code-interpreter';

const sandbox = await Sandbox.betaCreate(
    {
        timeoutMs: 5_000,
        autoPause: true
    },
);
console.log('Sandbox created', sandbox.sandboxId)

console.log('Waiting for 10 seconds...')
await new Promise(resolve => setTimeout(resolve, 10000));

const resumedSandbox = await Sandbox.connect(sandbox.sandboxId)
console.log('Sandbox resumed', resumedSandbox.sandboxId)

await sandbox.kill()

启用自动恢复功能

您可以在创建沙箱实例时设置 metadata 中的 auto_resume 键值为 true 启用自动恢复功能。启用后,当您尝试操作已暂停的沙箱(如执行命令、运行代码、文件操作等)时,沙箱会自动恢复。
注意:恢复后的沙箱默认超时时间为 5 分钟,可通过 setTimeoutset_timeout 方法调整沙箱的超时时间。
import { Sandbox } from 'ppio-sandbox/code-interpreter';

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

await sandbox.betaPause()
console.log('Sandbox paused', sandbox.sandboxId)

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

await sandbox.kill()