> ## Documentation Index
> Fetch the complete documentation index at: https://docs.cronho.st/llms.txt
> Use this file to discover all available pages before exploring further.

# Job Management

> Monitor and retrieve job execution details with the Cronhost SDK

# Job Management

Jobs represent individual executions of your scheduled HTTP requests. Each time a schedule runs (either automatically via cron or manually triggered), it creates a job that tracks the execution details, status, and results.

## Get All Jobs

Retrieve jobs with optional filtering parameters.

```typescript theme={null}
// Get all jobs
const allJobs = await cronhost.getJobs();

// Get jobs with filters
const filteredJobs = await cronhost.getJobs({
  scheduleId: 'schedule-123',
  status: 'SUCCESS',
  page: 1,
  limit: 50
});
```

**Parameters:**

* `params` (GetJobsParams, optional): Object containing filter options

**GetJobsParams fields** (all optional):

* `scheduleId` (string): Filter jobs by specific schedule ID
* `status` ("PENDING" | "RUNNING" | "SUCCESS" | "FAILED"): Filter by job status
* `page` (number): Page number for pagination (default: 1)
* `limit` (number): Number of jobs per page (default: 10, max: 100)

**Returns:** `Promise<Job[]>`

## Get Job by ID

Retrieve detailed information about a specific job.

```typescript theme={null}
const job = await cronhost.getJob('job-id');
```

**Parameters:**

* `id` (string, required): The unique identifier of the job

**Returns:** `Promise<Job>`

## Job Status Types

Jobs can have one of four statuses:

* **PENDING**: Job is queued and waiting to execute
* **RUNNING**: Job is currently executing the HTTP request
* **SUCCESS**: Job completed successfully (HTTP status 2xx)
* **FAILED**: Job failed due to HTTP error, timeout, or network issue

## Example: Monitoring Job Execution

```typescript theme={null}
import { Cronhost } from 'cronhost';

const cronhost = new Cronhost({
  apiKey: 'your-api-key'
});

async function monitorJobs() {
  try {
    // Trigger a schedule to create a new job
    const job = await cronhost.triggerSchedule('schedule-id');
    console.log('Created job:', job.id);

    // Poll job status until completion
    let currentJob = job;
    while (currentJob.status === 'PENDING' || currentJob.status === 'RUNNING') {
      console.log(`Job ${currentJob.id} status: ${currentJob.status}`);
      
      // Wait 2 seconds before checking again
      await new Promise(resolve => setTimeout(resolve, 2000));
      
      // Fetch updated job status
      currentJob = await cronhost.getJob(job.id);
    }

    // Job completed
    console.log('Final job status:', currentJob.status);
    
    if (currentJob.status === 'SUCCESS') {
      console.log('Response status code:', currentJob.statusCode);
      console.log('Response body:', currentJob.response);
    } else if (currentJob.status === 'FAILED') {
      console.log('Error message:', currentJob.errorMessage);
    }

  } catch (error) {
    console.error('Monitoring error:', error.message);
  }
}

// Get recent failed jobs for a specific schedule
async function getFailedJobs(scheduleId: string) {
  const failedJobs = await cronhost.getJobs({
    scheduleId,
    status: 'FAILED',
    limit: 20
  });

  console.log(`Found ${failedJobs.length} failed jobs for schedule ${scheduleId}`);
  
  failedJobs.forEach(job => {
    console.log(`Job ${job.id}: ${job.errorMessage}`);
  });
}

// Get jobs across all schedules with pagination
async function getAllJobsPaginated() {
  let page = 1;
  let allJobs: Job[] = [];
  
  while (true) {
    const jobs = await cronhost.getJobs({
      page,
      limit: 100
    });
    
    if (jobs.length === 0) break;
    
    allJobs.push(...jobs);
    page++;
  }
  
  console.log(`Retrieved ${allJobs.length} total jobs`);
  return allJobs;
}

monitorJobs();
```

## Job Object Structure

Each job contains detailed execution information:

```typescript theme={null}
interface Job {
  id: string;                    // Unique job identifier
  scheduleId: string;           // Associated schedule ID
  status: "PENDING" | "RUNNING" | "SUCCESS" | "FAILED";
  scheduledRunAtUtc: Date;      // When the job was supposed to run
  attemptNumber: number;        // Current retry attempt (1-based)
  httpMethod: "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
  endpoint: string;             // Target endpoint URL
  body?: string;                // Request body (if applicable)
  headers?: string;             // Request headers as JSON string
  statusCode?: number;          // HTTP response status code
  response?: string;            // HTTP response body
  startedAtUtc?: Date;         // When execution started
  completedAtUtc?: Date;       // When execution completed
  errorMessage?: string;        // Error details (if failed)
  createdAt: Date;             // Job creation timestamp
  updatedAt: Date;             // Last update timestamp
}
```

## Error Handling

When monitoring jobs, handle potential errors:

```typescript theme={null}
async function safeGetJob(jobId: string) {
  try {
    const job = await cronhost.getJob(jobId);
    return job;
  } catch (error) {
    if (error.message.includes('not found')) {
      console.log('Job not found');
      return null;
    }
    throw error; // Re-throw other errors
  }
}
```
