Skip to main content

Cron Job Execution

Cron Job Executions are historical records of each time a cron job runs. They capture the execution status, console logs, return values, timing information, and any errors that occurred.

At a Glance

  • Records every scheduled and manual execution
  • Captures console output and script return values
  • Tracks execution duration and status
  • Supports filtering by status and trigger type
  • Useful for debugging and monitoring

Data Shape

// apps/azalt/src/server/db/types/cron-job.ts (simplified)
interface CronJobExecution {
  id: string;
  cronJobId: string;
  status: "running" | "success" | "failed" | "timeout";
  triggerType: "scheduled" | "manual";
  triggeredById: string | null;    // User ID for manual triggers
  startedAt: Date;
  finishedAt: Date | null;
  executionTimeMs: number | null;  // Duration in milliseconds
  logs: string | null;             // Console output
  error: string | null;            // Error message if failed
  output: JsonValue | null;        // Return value from script
}

Execution Status

StatusDescription
runningCurrently executing (in progress)
successCompleted without errors
failedTerminated due to an error
timeoutExceeded 5-minute time limit

Trigger Types

TypeDescriptiontriggeredById
scheduledAutomatic execution by schedulernull
manualUser-initiated via UI or APIUser’s ID

Logs and Output

Console Logs: All console.log(), console.error(), etc. calls are captured:
// In your cron job code
console.log('Starting data sync...');
console.log(`Processing ${items.length} items`);
console.error('Warning: API rate limit approaching');

// These appear in execution.logs as:
// [2024-01-15T10:30:00.000Z] Starting data sync...
// [2024-01-15T10:30:01.234Z] Processing 150 items
// [2024-01-15T10:30:02.567Z] Warning: API rate limit approaching
Return Value: The script’s return value is stored in output:
// In your cron job code
const results = await processData();
return {
  processed: results.length,
  errors: results.filter(r => r.error).length,
  timestamp: new Date().toISOString()
};

// This object is stored in execution.output

Execution Statistics

The parent CronJob includes aggregated statistics from executions:
interface ExecutionStats {
  totalExecutions: number;      // All-time execution count
  successCount: number;         // Successful executions
  failedCount: number;          // Failed executions
  lastSuccess: Date | null;     // Most recent success
  lastFailure: Date | null;     // Most recent failure
  avgExecutionTimeMs: number | null;  // Average duration
}

Security & Permissions

  • View: Any organization member can view execution history
  • Create: System only (via scheduler or manual trigger)
  • Delete: Not supported (audit trail preserved)

API Notes

  • cronJob.listExecutions: Paginated list with filtering by status and trigger type
  • cronJob.getExecution: Full execution details including logs and output
  • cronJob.get: Includes recent executions and aggregated statistics

Monitoring Best Practices

  1. Check failure patterns: Look for recurring errors at specific times
  2. Monitor execution duration: Sudden increases may indicate issues
  3. Review logs regularly: Catch warnings before they become failures
  4. Set up alerts: Use the output to trigger external monitoring
  5. Track success rates: Calculate successCount / totalExecutions

Example: Debugging a Failed Execution

// Get execution details via API
const execution = await api.cronJob.getExecution({ id: 'exec-123' });

// Check status and error
if (execution.status === 'failed') {
  console.log('Error:', execution.error);
  console.log('Logs:', execution.logs);
  console.log('Duration:', execution.executionTimeMs, 'ms');
}

// For timeout issues
if (execution.status === 'timeout') {
  console.log('Job exceeded 5-minute limit');
  console.log('Last logged output:', execution.logs);
}
  • CronJob - Parent scheduled automation job
  • CronJobVariable - Environment variables and secrets