The sandboxes are by default kept alive only when connected to them. When you disconnect from a sandbox, it will be destroyed.If you want to keep the sandbox alive even after disconnecting from it, you can explicitly say for how long you want to keep it alive. You can then disconnect from the sandbox and reconnect to it later. This can be useful for example in a serverless environment or chatbot application.The duration limit to keep the sandbox alive is 1 hour. If you need more, feel free to reach out to us with your use.
The example below shows how to disconnect from a running sandbox and reconnect to it again while keeping the sandbox alive.
Copy
Ask AI
import { Sandbox } from 'e2b'async function wait(ms) { return new Promise(resolve => setTimeout(resolve, ms))}const sandbox = await Sandbox.create({ template: 'base' })
Call the keep_alive/keepAlive method on the sandbox instance to keep it alive. You can specify the preferred duration, as a multiple of a default time unit, which is
1ms in JS
1s in Python.
You then disconnect from the sandbox.
Copy
Ask AI
// Do something in the sandboxawait sandbox.filesystem.write('hello.txt', 'Hello World!')// Get the sandbox ID, we'll need it laterconst sandboxID = sandbox.id// Keep alive the sandbox for 2 minutesawait sandbox.keepAlive(2 * 60 * 1000) // 2 minutes// Close the sandbox. Even if we close the sandbox, it will stay alive, because we explicitly called keepAlive().await sandbox.close()// Do something else...await wait(60 * 1000)
You can then reconnect to the sandbox from anywhere.
Copy
Ask AI
// Reconnect to the sandboxconst sandbox2 = await Sandbox.reconnect(sandboxID)// Continue in using the sandboxconst content = await sandbox2.filesystem.read('hello.txt')console.log(content)// Close the sandboxawait sandbox2.close()
Sandbox metadata can be very useful to store information about the sandbox. You can use it to store the user ID or any other information you need to keep track of and then use this info for reconnecting to the sandbox. You can read more about sandbox metadata here.