Skip to main content
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:
  • Python
  • JavaScript
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()

Checking Process Status

Check the status of background processes:
  • Python
  • JavaScript
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()

Process Naming

Name your processes for easier identification:
  • Python
  • JavaScript
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()

Environment Variables

Pass environment variables to background execution:
  • Python
  • JavaScript
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()

Timeout Configuration

Set timeout for background execution:
  • Python
  • JavaScript
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()

Complete Example

Here’s a complete example showing background execution workflow:
  • Python
  • JavaScript
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()

Best Practices

1

1. Use Descriptive Names

Always name your background processes for easier identification when listing and managing them.
2

2. Set Appropriate Timeouts

Set timeouts based on expected execution time. Default is 5 minutes, but you can extend for longer tasks.
3

3. Monitor Status Regularly

Check process status periodically to track progress and handle completion or failures.
4

4. Clean Up Completed Processes

Remove completed processes to keep your process list manageable. Use Process Management for cleanup.
5

5. Handle Failures

Always check for failed status and handle errors appropriately. Access stderr for error details.

Implementation

Next Steps