Running tasks asynchronously
When you setasync: true, the API returns immediately with a confirmation that the task has started. You can then poll for execution results using the task execution history endpoint.
// Run the task asynchronously
const execution = await client.task.run({
taskId: taskId,
version: '1',
async: true, // Enable async execution
inputs: {
ANCHOR_TARGET_URL: 'https://example.com',
ANCHOR_MAX_PAGES: '10'
}
});
console.log('Task execution started:', execution.data);
// Response: { async: true, success: true, message: 'Task execution started', taskId: '...' }
# Run the task asynchronously
execution = client.task.run(
task_id=task_id,
version="1",
async_=True, # Enable async execution
inputs={
"ANCHOR_TARGET_URL": "https://example.com",
"ANCHOR_MAX_PAGES": "10"
}
)
print(f"Task execution started: {execution.data}")
# Response: {'async': True, 'success': True, 'message': 'Task execution started', 'taskId': '...'}
Checking execution results
After starting an async task, you can check its execution status and results by querying the task’s execution history endpoint:// Get execution results
const response = await fetch(`https://api.anchorbrowser.io/v1/task/${taskId}/executions?page=1&limit=1&version=1`, {
headers: {
'anchor-api-key': process.env.ANCHORBROWSER_API_KEY,
'Content-Type': 'application/json'
}
});
const results = await response.json();
console.log('Execution results:', results.data);
import os
import requests
# Get execution results
response = requests.get(
f"https://api.anchorbrowser.io/v1/task/{task_id}/executions",
params={
# "status": "success", #Optional: filter by status (success, failure, timeout, cancelled)
"page": 1,
"limit": 1,
"version": "1" # Optional: filter by version
},
headers={
"anchor-api-key": os.environ.get("ANCHORBROWSER_API_KEY"),
"Content-Type": "application/json"
}
)
results = response.json()
print(f"Execution results: {results['data']}")
{
"data": {
"results": [
{
"id": "550e8400-e29b-41d4-a716-446655440000",
"status": "success",
"executionTime": 5234,
"output": "{\"success\": true, \"message\": \"Task completed successfully\"}",
"errorMessage": null,
"startTime": "2024-01-15T10:30:00Z"
}
],
"pagination": {
"page": 1,
"limit": 1,
"total": 1,
"totalPages": 1
}
}
}
Async task executions have a maximum duration of 3 hours. Tasks that exceed this limit will be automatically cancelled.Note: Tasks must be deployed (not just in draft) to appear in the execution results list.
Polling for results
For async tasks, you can implement polling to wait for completion:// Poll for task completion
async function waitForTaskCompletion(taskId: string, maxAttempts: number = 60) {
for (let i = 0; i < maxAttempts; i++) {
const response = await fetch(`https://api.anchorbrowser.io/v1/task/${taskId}/executions?page=1&limit=1`, {
headers: {
'anchor-api-key': process.env.ANCHORBROWSER_API_KEY,
'Content-Type': 'application/json'
}
});
const results = await response.json();
const latestResult = results.data?.results?.[0];
if (latestResult) {
if (latestResult.status === 'success' || latestResult.status === 'failure') {
return latestResult;
}
}
// Wait 2 seconds before next poll
await new Promise(resolve => setTimeout(resolve, 2000));
}
throw new Error('Task execution timeout');
}
// Usage
const execution = await client.task.run({
taskId: taskId,
version: '1',
async: true,
inputs: { ANCHOR_TARGET_URL: 'https://example.com' }
});
const result = await waitForTaskCompletion(taskId);
console.log('Task completed:', result);
import os
import time
import requests
# Poll for task completion
def wait_for_task_completion(task_id: str, max_attempts: int = 60):
for _ in range(max_attempts):
response = requests.get(
f"https://api.anchorbrowser.io/v1/task/{task_id}/executions",
params={"page": 1, "limit": 1},
headers={
"anchor-api-key": os.environ.get("ANCHORBROWSER_API_KEY"),
"Content-Type": "application/json"
}
)
results = response.json()
latest_result = results['data']['results'][0] if results['data']['results'] else None
if latest_result:
if latest_result['status'] in ['success', 'failure']:
return latest_result
# Wait 2 seconds before next poll
time.sleep(2)
raise Exception('Task execution timeout')
# Usage
execution = client.task.run(
task_id=task_id,
version="1",
async_=True,
inputs={"ANCHOR_TARGET_URL": "https://example.com"}
)
result = wait_for_task_completion(task_id)
print(f"Task completed: {result}")

