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

# Scheduler

> Schedule periodic agent and recipe execution in TypeScript

# Scheduler (TypeScript)

Schedule agents and recipes to run periodically. Perfect for monitoring tasks, periodic reports, and automated workflows.

## Installation

```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
npm install praisonai-ts
```

## Basic Usage

### Scheduling a Recipe

```typescript theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
import { recipe } from 'praisonai-ts';

// Schedule a recipe
const scheduler = await recipe.schedule('my-recipe', {
  interval: 'hourly',
  maxRetries: 3,
  timeoutSec: 300,
  maxCostUsd: 1.00,
  runImmediately: true,
});

// Start the scheduler
scheduler.start();

// Get statistics
const stats = scheduler.getStats();
console.log(`Executions: ${stats.totalExecutions}`);
console.log(`Success rate: ${stats.successRate}%`);

// Stop when done
scheduler.stop();
```

### Scheduler Interface

```typescript theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
interface RecipeScheduler {
  recipeName: string;
  interval: string;
  isRunning: boolean;
  
  start(): void;
  stop(): void;
  getStats(): SchedulerStats;
}

interface SchedulerStats {
  totalExecutions: number;
  successfulExecutions: number;
  failedExecutions: number;
  successRate: number;
  totalCost: number;
  lastExecutionAt?: Date;
  nextExecutionAt?: Date;
}
```

## Using AgentScheduler Directly

```typescript theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
import { Agent, AgentScheduler } from 'praisonai-ts';

// Create agent
const agent = new Agent({
  name: 'News Monitor',
  instructions: 'Monitor and summarize AI news',
});

// Create scheduler
const scheduler = new AgentScheduler({
  agent,
  task: 'Check for latest AI news',
  timeout: 300,
  maxCost: 1.00,
});

// Start with interval
scheduler.start({
  scheduleExpr: 'hourly',
  maxRetries: 3,
  runImmediately: true,
});

// Monitor
console.log(`Running: ${scheduler.isRunning}`);
console.log(`Stats: ${JSON.stringify(scheduler.getStats())}`);

// Stop
scheduler.stop();
```

## Interval Formats

| Format   | Description        |
| -------- | ------------------ |
| `hourly` | Every hour         |
| `daily`  | Every day          |
| `*/30m`  | Every 30 minutes   |
| `*/6h`   | Every 6 hours      |
| `3600`   | Every 3600 seconds |

## Configuration

### TEMPLATE.yaml Runtime Block

```yaml theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
runtime:
  schedule:
    enabled: true
    interval: "hourly"
    max_retries: 3
    run_immediately: false
    timeout_sec: 300
    max_cost_usd: 1.00
```

### Safe Defaults

| Setting      | Default | Description               |
| ------------ | ------- | ------------------------- |
| `interval`   | hourly  | Execution interval        |
| `maxRetries` | 3       | Retry attempts on failure |
| `timeoutSec` | 300     | Timeout per execution     |
| `maxCostUsd` | 1.00    | Budget limit              |

## Error Handling

```typescript theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
import { recipe, SchedulerError } from 'praisonai-ts';

try {
  const scheduler = await recipe.schedule('my-recipe', {
    interval: 'hourly',
    maxCostUsd: 0.50,
  });
  
  scheduler.start();
  
  // Monitor for errors
  scheduler.on('error', (error) => {
    console.error(`Execution failed: ${error.message}`);
  });
  
  scheduler.on('budgetExceeded', () => {
    console.log('Budget limit reached, stopping');
    scheduler.stop();
  });
  
} catch (error) {
  if (error instanceof SchedulerError) {
    console.error(`Scheduler error: ${error.message}`);
  }
}
```

## Best Practices

1. **Set budget limits** - Prevent runaway costs
2. **Use appropriate intervals** - Match task requirements
3. **Handle failures** - Implement retry logic
4. **Monitor statistics** - Track success rates
5. **Clean shutdown** - Always call stop() when done

## See Also

* [Scheduler CLI](/docs/js/scheduler-cli) - CLI commands
* [Background Tasks](/docs/js/background-tasks) - One-time background tasks
* [Async Jobs](/docs/js/async-jobs) - Server-based job execution
