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

# Cron Job

> Scheduled automation scripts that run at specified intervals within your organization.

### Cron Job

Cron Jobs are scheduled automation scripts that execute JavaScript code at regular intervals. They enable organizations to automate data synchronization, calculations, notifications, and integrations with external systems.

#### At a Glance

* JavaScript code runs in a secure sandbox environment
* Configurable schedules: 5m, 10m, 15m, 30m, 1h, 2h, 4h, 6h, 12h, daily, weekly
* Access to organization data, database operations, HTTP client, and email
* Environment variables and encrypted secrets support
* 5-minute maximum execution time
* Manual trigger option for testing

#### Data Shape

```typescript theme={null}
// apps/azalt/src/server/db/types/cron-job.ts (simplified)
interface CronJob {
  id: string;
  name: string;
  description: string | null;
  code: string;                    // JavaScript code to execute
  schedule: CronJobSchedule;       // Execution frequency
  isActive: boolean;               // Enable/disable execution
  organizationId: string;
  createdById: string;
  lastExecutionAt: Date | null;    // Last run timestamp
  nextExecutionAt: Date | null;    // Next scheduled run
  metadata: JsonValue | null;      // Custom metadata
}

type CronJobSchedule =
  | "5m"   // Every 5 minutes
  | "10m"  // Every 10 minutes
  | "15m"  // Every 15 minutes
  | "30m"  // Every 30 minutes
  | "1h"   // Every hour
  | "2h"   // Every 2 hours
  | "4h"   // Every 4 hours
  | "6h"   // Every 6 hours
  | "12h"  // Every 12 hours
  | "1d"   // Daily
  | "1w";  // Weekly
```

#### Sandbox Environment

Your JavaScript code runs in an isolated sandbox with access to these APIs:

| API            | Description                                                   |
| -------------- | ------------------------------------------------------------- |
| `organization` | Current organization data and sites                           |
| `db`           | Database operations (scoped to organization via RLS)          |
| `fetch`        | HTTP client for external API calls                            |
| `email`        | Send notification emails                                      |
| `env`          | Environment variables (CronJobVariables with type "variable") |
| `secrets`      | Encrypted secret values (CronJobVariables with type "secret") |
| `console`      | Logging (captured in execution logs)                          |

#### Example Code

```javascript theme={null}
// Sync data from external API
const response = await fetch('https://api.example.com/data', {
  headers: { 'Authorization': `Bearer ${secrets.API_KEY}` }
});

const data = await response.json();
console.log(`Fetched ${data.items.length} items`);

// Process and store data
for (const item of data.items) {
  await db.insertInto('CustomTable')
    .values({ externalId: item.id, value: item.value })
    .execute();
}

// Send notification
await email.send({
  to: env.ADMIN_EMAIL,
  subject: 'Data Sync Complete',
  body: `Synced ${data.items.length} items successfully.`
});

return { synced: data.items.length };
```

#### Security & Permissions

* **Create/Update/Delete**: Owner role required
* **View/Execute**: Any organization member
* **Sandbox**: Code runs in isolated VM with no file system access
* **RLS**: Database queries respect row-level security policies
* **Secrets**: Encrypted at rest using organization's encryption key
* **Timeout**: Automatic termination after 5 minutes

#### Execution Flow

1. Scheduler finds jobs where `nextExecutionAt <= now` and `isActive = true`
2. Job code is executed in a secure sandbox
3. Execution result (success/failure, logs, output) is recorded
4. `nextExecutionAt` is calculated based on schedule
5. `lastExecutionAt` is updated

#### API Notes

* `cronJob.list`: Returns jobs with execution statistics and variable counts
* `cronJob.get`: Returns full job details including code and recent executions
* `cronJob.create`: Creates new job (starts inactive for safety)
* `cronJob.execute`: Manually trigger execution (useful for testing)
* `cronJob.toggle`: Enable/disable scheduled execution

#### Related Concepts

* CronJobVariable - Environment variables and secrets for jobs
* CronJobExecution - Execution history and logs
