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

# Scheduler

> Schedule periodic agent and recipe execution in TypeScript

Schedule agents and recipes to run periodically.

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
graph LR
    Scheduler[Scheduler] --> Agent[Agent]
    Agent --> Job([Scheduled Job])

    classDef agent fill:#8B0000,stroke:#7C90A0,color:#fff
    classDef tool fill:#189AB4,stroke:#7C90A0,color:#fff

    class Agent agent
    class Scheduler,Job tool
    classDef agent fill:#8B0000,color:#fff
    classDef tool fill:#189AB4,color:#fff
```

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

## Quick Start

<Steps>
  <Step title="Simple 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;
    }
    ```
  </Step>
</Steps>

## 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

<AccordionGroup>
  <Accordion title="Set budget limits">
    Prevent runaway costs
  </Accordion>

  <Accordion title="Use appropriate intervals">
    Match task requirements
  </Accordion>

  <Accordion title="Handle failures">
    Implement retry logic
  </Accordion>

  <Accordion title="Monitor statistics">
    Track success rates
  </Accordion>

  <Accordion title="Clean shutdown">
    Always call stop() when done
  </Accordion>
</AccordionGroup>

## Related

<CardGroup cols={2}>
  <Card title="Scheduler CLI" icon="terminal" href="/docs/js/scheduler-cli">
    CLI commands
  </Card>

  <Card title="Async Jobs" icon="clock" href="/docs/js/async-jobs">
    Server jobs
  </Card>
</CardGroup>
