Documentation Index
Fetch the complete documentation index at: https://docs.hopx.ai/llms.txt
Use this file to discover all available pages before exploring further.
Background execution allows you to start code execution and return immediately, without waiting for completion. This is ideal for long-running tasks that you want to monitor and manage separately.
Prerequisites
Before you begin, make sure you have:
- Active sandbox - A running sandbox (see Creating Sandboxes)
- Understanding of synchronous execution - Familiarity with Synchronous Execution is helpful
- Long-running task - Code that takes more than a few minutes to complete
Overview
Background execution is perfect for:
- Long-running computations (>5 minutes)
- Tasks that don’t need immediate results
- Parallel processing of multiple tasks
- Workflows where you want to check status periodically
Background execution returns immediately with a process_id. Use Process Management to check status and manage background processes.
Starting Background Execution
Start code execution in the background:
from hopx_ai import Sandbox
sandbox = Sandbox.create(template="code-interpreter")
# Start background execution
result = sandbox.run_code_background(
code='''
import time
for i in range(10):
print(f"Step {i+1}/10")
time.sleep(2)
print("Done!")
''',
language='python',
name='long-task'
)
process_id = result['process_id']
print(f"Process started: {process_id}")
print(f"Status: {result['status']}")
sandbox.kill()
import { Sandbox } from '@hopx-ai/sdk';
const sandbox = await Sandbox.create({ template: 'code-interpreter' });
// Start background execution
const result = await sandbox.runCodeBackground(
`
import time
for i in range(10):
print(f"Step {i+1}/10")
time.sleep(2)
print("Done!")
`,
{
language: 'python',
name: 'long-task'
}
);
const processId = result.processId;
console.log(`Process started: ${processId}`);
console.log(`Status: ${result.status}`);
await sandbox.kill();
Checking Process Status
Check the status of background processes:
from hopx_ai import Sandbox
import time
sandbox = Sandbox.create(template="code-interpreter")
# Start background task
result = sandbox.run_code_background(
code='import time; time.sleep(30); print("Done")',
language='python',
name='check-status-demo'
)
process_id = result['process_id']
# Check status periodically
for i in range(5):
processes = sandbox.list_processes()
for proc in processes:
if proc['process_id'] == process_id:
print(f"Status: {proc['status']}")
if proc['status'] == 'completed':
print(f"Output: {proc.get('stdout', '')}")
break
time.sleep(2)
sandbox.kill()
import { Sandbox } from '@hopx-ai/sdk';
const sandbox = await Sandbox.create({ template: 'code-interpreter' });
// Start background task
const result = await sandbox.runCodeBackground(
'import time; time.sleep(30); print("Done")',
{
language: 'python',
name: 'check-status-demo'
}
);
const processId = result.processId;
// Check status periodically
for (let i = 0; i < 5; i++) {
const processes = await sandbox.listProcesses();
const proc = processes.find(p => p.processId === processId);
if (proc) {
console.log(`Status: ${proc.status}`);
if (proc.status === 'completed') {
console.log(`Output: ${proc.stdout || ''}`);
break;
}
}
await new Promise(resolve => setTimeout(resolve, 2000));
}
await sandbox.kill();
Process Naming
Name your processes for easier identification:
from hopx_ai import Sandbox
sandbox = Sandbox.create(template="code-interpreter")
# Start multiple named processes
proc1 = sandbox.run_code_background(
code='import time; time.sleep(60)',
language='python',
name='data-processing'
)
proc2 = sandbox.run_code_background(
code='import time; time.sleep(60)',
language='python',
name='ml-training'
)
# List processes by name
processes = sandbox.list_processes()
for proc in processes:
print(f"{proc.get('name', 'unnamed')}: {proc['status']}")
sandbox.kill()
import { Sandbox } from '@hopx-ai/sdk';
const sandbox = await Sandbox.create({ template: 'code-interpreter' });
// Start multiple named processes
const proc1 = await sandbox.runCodeBackground(
'import time; time.sleep(60)',
{
language: 'python',
name: 'data-processing'
}
);
const proc2 = await sandbox.runCodeBackground(
'import time; time.sleep(60)',
{
language: 'python',
name: 'ml-training'
}
);
// List processes by name
const processes = await sandbox.listProcesses();
for (const proc of processes) {
console.log(`${proc.name || 'unnamed'}: ${proc.status}`);
}
await sandbox.kill();
Environment Variables
Pass environment variables to background execution:
from hopx_ai import Sandbox
sandbox = Sandbox.create(template="code-interpreter")
# Start background task with environment variables
result = sandbox.run_code_background(
code='''
import os
import time
api_key = os.getenv("API_KEY")
print(f"Using API key: {api_key[:10]}...")
time.sleep(30)
print("Task completed")
''',
language='python',
env={
"API_KEY": "sk-123456",
"DEBUG": "true"
},
name='env-demo'
)
print(f"Process ID: {result['process_id']}")
sandbox.kill()
import { Sandbox } from '@hopx-ai/sdk';
const sandbox = await Sandbox.create({ template: 'code-interpreter' });
// Start background task with environment variables
const result = await sandbox.runCodeBackground(
`
import os
import time
api_key = os.getenv("API_KEY")
print(f"Using API key: {api_key[:10]}...")
time.sleep(30)
print("Task completed")
`,
{
language: 'python',
env: {
API_KEY: 'sk-123456',
DEBUG: 'true'
},
name: 'env-demo'
}
);
console.log(`Process ID: ${result.processId}`);
await sandbox.kill();
Timeout Configuration
Set timeout for background execution:
from hopx_ai import Sandbox
sandbox = Sandbox.create(template="code-interpreter")
# Start background task with 10 minute timeout
result = sandbox.run_code_background(
code='import time; time.sleep(300)',
language='python',
timeout=600, # 10 minutes
name='long-task'
)
print(f"Process started with {result.get('timeout', 'default')}s timeout")
sandbox.kill()
import { Sandbox } from '@hopx-ai/sdk';
const sandbox = await Sandbox.create({ template: 'code-interpreter' });
// Start background task with 10 minute timeout
const result = await sandbox.runCodeBackground(
'import time; time.sleep(300)',
{
language: 'python',
timeout: 600, // 10 minutes
name: 'long-task'
}
);
console.log(`Process started with ${result.timeout || 'default'}s timeout`);
await sandbox.kill();
Complete Example
Here’s a complete example showing background execution workflow:
from hopx_ai import Sandbox
import time
sandbox = Sandbox.create(template="code-interpreter")
# Start background task
result = sandbox.run_code_background(
code='''
import time
import random
for i in range(20):
value = random.randint(1, 100)
print(f"Step {i+1}: Generated {value}")
time.sleep(1)
print("All done!")
''',
language='python',
timeout=300,
name='random-generator',
env={"SEED": "42"}
)
process_id = result['process_id']
print(f"✅ Background task started: {process_id}")
# Monitor progress
while True:
processes = sandbox.list_processes()
proc = next((p for p in processes if p['process_id'] == process_id), None)
if not proc:
print("Process not found")
break
status = proc['status']
print(f"Status: {status}")
if status == 'completed':
print(f"✅ Task completed!")
print(f"Output:\n{proc.get('stdout', '')}")
break
elif status == 'failed':
print(f"❌ Task failed!")
print(f"Error: {proc.get('stderr', '')}")
break
time.sleep(2)
sandbox.kill()
import { Sandbox } from '@hopx-ai/sdk';
const sandbox = await Sandbox.create({ template: 'code-interpreter' });
// Start background task
const result = await sandbox.runCodeBackground(
`
import time
import random
for i in range(20):
value = random.randint(1, 100)
print(f"Step {i+1}: Generated {value}")
time.sleep(1)
print("All done!")
`,
{
language: 'python',
timeout: 300,
name: 'random-generator',
env: { SEED: '42' }
}
);
const processId = result.processId;
console.log(`✅ Background task started: ${processId}`);
// Monitor progress
while (true) {
const processes = await sandbox.listProcesses();
const proc = processes.find(p => p.processId === processId);
if (!proc) {
console.log('Process not found');
break;
}
const status = proc.status;
console.log(`Status: ${status}`);
if (status === 'completed') {
console.log('✅ Task completed!');
console.log(`Output:\n${proc.stdout || ''}`);
break;
} else if (status === 'failed') {
console.log('❌ Task failed!');
console.log(`Error: ${proc.stderr || ''}`);
break;
}
await new Promise(resolve => setTimeout(resolve, 2000));
}
await sandbox.kill();
Best Practices
1. Use Descriptive Names
Always name your background processes for easier identification when listing and managing them.
2. Set Appropriate Timeouts
Set timeouts based on expected execution time. Default is 5 minutes, but you can extend for longer tasks.
3. Monitor Status Regularly
Check process status periodically to track progress and handle completion or failures.
4. Clean Up Completed Processes
Remove completed processes to keep your process list manageable. Use Process Management for cleanup. 5. Handle Failures
Always check for failed status and handle errors appropriately. Access stderr for error details.
Implementation
Next Steps