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

# Scheduled Tasks

> Automate agent execution with flexible scheduling options

## What You'll Learn

This guide shows you how to automate agent workflows using **Scheduled Tasks** powered by **Celery RedBeat**. Your agents can run automatically on specific schedules, saving time and ensuring consistent execution.

<Info>
  **Prerequisites**:

  * Admin role in Junis (for creating schedules)
  * At least one configured agent (Orchestrator recommended)
  * Understanding of basic cron syntax (optional, for CRON schedules)
</Info>

***

## What are Scheduled Tasks?

**Scheduled Tasks** enable you to run agent workflows automatically at specific times or intervals without manual triggering.

### Real-World Example

**Without Scheduled Tasks**:

```
8:00 AM: Manually open Junis chat
8:02 AM: Type "Generate daily sales report"
8:05 AM: Wait for agent to complete
8:07 AM: Copy report and send to team

...repeat every day
```

**With Scheduled Tasks**:

```
One-time setup:
- Create schedule: "Generate daily sales report" at 8:00 AM
- Agent runs automatically every day
- Results saved to dedicated session
- View report anytime in chat history
```

**Benefits**:

* ⏰ **Time savings**: No manual execution needed
* 📊 **Consistency**: Same task runs at exact same time
* 📝 **History tracking**: All execution results saved in sessions
* 🔄 **Flexibility**: Adjust schedules without code changes

***

## How Scheduling Works

### Architecture Overview

Junis uses **Celery** (distributed task queue) + **RedBeat** (dynamic scheduler) + **Redis** (storage) for robust scheduling.

```mermaid theme={null}
graph TB
    A[Admin UI] -->|Create Schedule| B[FastAPI API]
    B -->|Save to DB| C[PostgreSQL]
    B -->|Register with| D[RedBeat Scheduler]
    D -->|Store metadata in| E[Redis]
    D -->|At scheduled time| F[Celery Worker]
    F -->|Execute| G[Orchestrator Agent]
    G -->|Save results to| H[Chat Session]
    H -->|View in| I[Chat UI]
```

### Key Components

<CardGroup cols={2}>
  <Card title="Celery" icon="gear">
    **Distributed Task Queue**

    Manages background task execution across multiple workers.
  </Card>

  <Card title="RedBeat" icon="clock">
    **Dynamic Scheduler**

    Stores schedules in Redis, allows runtime modification without restart.
  </Card>

  <Card title="PostgreSQL" icon="database">
    **Schedule Storage**

    Stores schedule definitions, execution history, metadata.
  </Card>

  <Card title="Redis" icon="bolt">
    **Metadata Cache**

    Stores RedBeat scheduler state, provides fast access.
  </Card>
</CardGroup>

### Execution Flow

<Steps>
  <Step title="Schedule Creation">
    Admin creates schedule via UI or API. Schedule saved to PostgreSQL + registered with RedBeat.
  </Step>

  <Step title="RedBeat Monitoring">
    RedBeat continuously checks Redis for schedules due to run. Uses distributed lock to prevent duplicate execution.
  </Step>

  <Step title="Task Execution">
    When scheduled time arrives, RedBeat triggers Celery worker to execute task.
  </Step>

  <Step title="Agent Processing">
    Celery worker calls Orchestrator agent with saved prompt. Agent processes using configured workflow.
  </Step>

  <Step title="Result Storage">
    Agent response saved to chat session. Execution status recorded in `scheduled_task_runs` table.
  </Step>
</Steps>

***

## Schedule Types

Junis supports 6 schedule types for different use cases:

<Tabs>
  <Tab title="ONCE">
    **One-Time Execution**

    Run task immediately or at a specific future time.

    **Use Cases**:

    * Reminder at specific date/time
    * One-off report generation
    * Testing scheduled workflows

    **Configuration**:

    ```json theme={null}
    {
      "schedule_type": "ONCE",
      "schedule_config": {
        "execute_at": "2026-01-01 23:59:00"  // Optional
      }
    }
    ```

    **Behavior**:

    * If `execute_at` not provided: Runs immediately
    * If `execute_at` provided: Runs at specified time
    * Automatically disabled after execution
  </Tab>

  <Tab title="EVERY_MINUTES">
    **Run Every N Minutes**

    Run task at fixed minute intervals.

    **Use Cases**:

    * Real-time monitoring (every 5 minutes)
    * Frequent data sync (every 15 minutes)
    * High-frequency alerts (every 1 minute)

    **Configuration**:

    ```json theme={null}
    {
      "schedule_type": "EVERY_MINUTES",
      "schedule_config": {
        "interval": 15  // Run every 15 minutes
      }
    }
    ```

    **Example**: `{"interval": 5}` = Run every 5 minutes

    <Warning>
      **Resource Usage**: Frequent schedules (every 1-5 minutes) consume more resources. Use sparingly.
    </Warning>
  </Tab>

  <Tab title="EVERY_HOURS">
    **Run Every N Hours**

    Run task at fixed hour intervals.

    **Use Cases**:

    * Hourly reports
    * Periodic data aggregation
    * Regular health checks

    **Configuration**:

    ```json theme={null}
    {
      "schedule_type": "EVERY_HOURS",
      "schedule_config": {
        "interval": 2  // Run every 2 hours
      }
    }
    ```

    **Example**: `{"interval": 4}` = Run every 4 hours
  </Tab>

  <Tab title="DAILY">
    **Daily at Specific Time**

    Run task every day at a specific hour and minute.

    **Use Cases**:

    * Daily reports (8 AM every day)
    * Nightly data backups (2 AM every day)
    * End-of-day summaries (6 PM every day)

    **Configuration**:

    ```json theme={null}
    {
      "schedule_type": "DAILY",
      "schedule_config": {
        "hour": 8,     // 0-23
        "minute": 0    // 0-59
      }
    }
    ```

    **Example**: `{"hour": 8, "minute": 30}` = 8:30 AM every day
  </Tab>

  <Tab title="WEEKLY">
    **Weekly on Specific Day**

    Run task once per week on a specific day of the week.

    **Use Cases**:

    * Weekly status reports (Monday 9 AM)
    * Weekly team sync summaries (Friday 5 PM)
    * Weekend data analysis (Saturday midnight)

    **Configuration**:

    ```json theme={null}
    {
      "schedule_type": "WEEKLY",
      "schedule_config": {
        "day_of_week": 1,  // 0=Sun, 1=Mon, 2=Tue, ..., 6=Sat
        "hour": 9,
        "minute": 0
      }
    }
    ```

    **Example**: `{"day_of_week": 1, "hour": 9, "minute": 0}` = Every Monday at 9:00 AM
  </Tab>

  <Tab title="MONTHLY">
    **Monthly on Specific Date**

    Run task once per month on a specific day of the month.

    **Use Cases**:

    * Monthly financial reports (1st of month)
    * Monthly performance reviews (Last Friday)
    * Quarterly business summaries (1st of quarter months)

    **Configuration**:

    ```json theme={null}
    {
      "schedule_type": "MONTHLY",
      "schedule_config": {
        "day_of_month": 1,  // 1-31
        "hour": 8,
        "minute": 0
      }
    }
    ```

    **Example**: `{"day_of_month": 1, "hour": 8, "minute": 0}` = 1st of every month at 8:00 AM

    <Warning>
      **Day 29-31**: For months without these days (e.g., February), task will run on last day of month.
    </Warning>
  </Tab>
</Tabs>

***

## Setting Up Scheduled Tasks

### Step-by-Step Guide

<Steps>
  <Step title="Navigate to Schedules Page">
    1. Log in to Junis as Admin
    2. Go to **Team Management** → **Task Planning**
    3. Click **"New Schedule"** or **"+ Add Schedule"** button
  </Step>

  <Step title="Configure Basic Information">
    **Schedule Name**:

    * Descriptive name (e.g., "Daily Sales Report")
    * Must be unique within your organization
    * Used for identification in schedule list

    **Prompt**:

    * The instruction/question sent to Orchestrator
    * Same as typing in chat interface
    * Can include specific parameters, agent names, etc.

    **Example Prompts**:

    ```
    "Generate daily sales summary for yesterday"
    "Check all open support tickets and create priority list"
    "Analyze top 10 trending products and send report via email"
    "Run DataAnalysisWorkflow for customer insights"
    ```
  </Step>

  <Step title="Choose Schedule Type">
    Select one of the 5 schedule types:

    <Tabs>
      <Tab title="ONCE">
        **Immediate or Future**:

        * Leave blank: Runs immediately
        * Set date/time: Runs at specific future time
      </Tab>

      <Tab title="DAILY">
        **Time Selection**:

        * Hour: 0-23 (24-hour format)
        * Minute: 0-59

        Example: `8:30` = 8:30 AM every day
      </Tab>

      <Tab title="WEEKLY">
        **Day & Time**:

        * Day of week: Sunday (0) to Saturday (6)
        * Hour & Minute

        Example: `Monday at 9:00 AM`
      </Tab>

      <Tab title="MONTHLY">
        **Date & Time**:

        * Day of month: 1-31
        * Hour & Minute

        Example: `1st of month at 8:00 AM`
      </Tab>

      <Tab title="CRON">
        **Custom Expression**:

        * Minute, Hour, Day of week, Day of month, Month
        * Use wildcards (`*`), ranges (`9-17`), lists (`0,30`)

        Example: `Every 30 minutes during business hours (9-5, Mon-Fri)`
      </Tab>
    </Tabs>
  </Step>

  <Step title="Configure Session Settings">
    **Two Options**:

    <Tabs>
      <Tab title="New Session (Recommended)">
        **Create fresh session for each execution**

        **Pros**:

        * ✅ Clean slate each time
        * ✅ Easy to find specific execution results
        * ✅ No context pollution from previous runs

        **Use Cases**:

        * Daily/weekly/monthly reports
        * Independent analysis tasks
        * One-off scheduled actions

        **Session Naming**:

        * Auto-generated: `Scheduled: {schedule_name} - {timestamp}`
        * Example: `Scheduled: Daily Sales Report - 2026-01-01 08:00`
      </Tab>

      <Tab title="Existing Session">
        **Use same session for all executions**

        **Pros**:

        * ✅ Continuous conversation thread
        * ✅ Agent remembers previous executions
        * ✅ Single place to view all history

        **Use Cases**:

        * Iterative analysis (agent learns over time)
        * Continuous monitoring (track changes)
        * Thread-based workflows

        **Configuration**:

        * Specify `session_id` of existing session
        * Session must exist before schedule creation
        * All executions append to this session
      </Tab>
    </Tabs>

    <Warning>
      **Session Limits**: Using existing session may cause very long conversation history. Consider starting new session periodically.
    </Warning>
  </Step>

  <Step title="Save and Activate">
    1. Review all settings
    2. Toggle **"Enabled"** switch to ON
    3. Click **"Create Schedule"** button

    **What Happens Next**:

    * Schedule saved to database
    * RedBeat registers schedule in Redis
    * Next run time calculated and displayed
    * Schedule appears in schedule list
  </Step>
</Steps>

***

## Monitoring Scheduled Tasks

### Schedule List View

**Location**: Admin → Schedules

**Columns Displayed**:

| Column        | Description         | Example                             |
| ------------- | ------------------- | ----------------------------------- |
| **Name**      | Schedule name       | "Daily Sales Report"                |
| **Type**      | Schedule type       | DAILY, WEEKLY, CRON                 |
| **Status**    | Enabled/Disabled    | 🟢 Enabled / 🔴 Disabled            |
| **Next Run**  | Next execution time | "2026-01-02 08:00:00"               |
| **Last Run**  | Last execution time | "2026-01-01 08:00:00"               |
| **Run Count** | Total executions    | 142                                 |
| **Actions**   | Quick actions       | Edit, Delete, Run Now, View History |

**Status Indicators**:

* 🟢 **Enabled**: Schedule active, will run at next scheduled time
* 🔴 **Disabled**: Schedule paused, will not run automatically
* ⏳ **Running**: Currently executing
* ✅ **Completed**: ONCE schedule that has finished

### Execution History

**Viewing History**:

1. Find schedule in list
2. Click **"View History"** or history icon
3. See list of all executions

**Execution Record Columns**:

| Column            | Description                              |
| ----------------- | ---------------------------------------- |
| **Status**        | PENDING, RUNNING, SUCCESS, FAILED        |
| **Started At**    | Execution start timestamp                |
| **Completed At**  | Execution end timestamp                  |
| **Duration**      | Time taken to complete                   |
| **Session Link**  | Direct link to chat session with results |
| **Error Message** | Error details (if failed)                |

**Status Meanings**:

* ⏳ **PENDING**: Task queued, waiting for worker
* ▶️ **RUNNING**: Currently executing
* ✅ **COMPLETED**: Completed successfully
* ❌ **FAILED**: Execution failed (see error message)

### Viewing Execution Results

**Method 1: From Execution History**:

1. Click session link in execution record
2. Opens chat session with that execution's conversation
3. View agent's response and any generated outputs

**Method 2: From Chat Sessions List**:

1. Go to **Chat** → **Sessions**
2. Filter by schedule name or date
3. Sessions named `Scheduled: {schedule_name} - {timestamp}`

**What You'll See**:

* User message: `[Scheduled] {prompt}`
* Agent response: Full conversation output
* Tool calls: Any tools used during execution
* Timestamps: Exact execution time

***

## Managing Scheduled Tasks

### Editing Schedules

<Steps>
  <Step title="Open Edit Dialog">
    In schedule list, click **Edit** icon (pencil) next to schedule name.
  </Step>

  <Step title="Modify Settings">
    **Can Change**:

    * Schedule name
    * Prompt
    * Schedule type and configuration
    * Session settings

    **Cannot Change**:

    * Organization (schedules are org-specific)
    * Creator (for audit purposes)
  </Step>

  <Step title="Save Changes">
    Click **"Save"** → Schedule updated in database and RedBeat re-registers with new settings.
  </Step>
</Steps>

**Effect of Changes**:

* **Next run time recalculated** based on new schedule
* **Existing execution history preserved**
* **Currently running execution not affected** (runs with old settings)

### Enabling/Disabling Schedules

**Toggle Switch**:

* In schedule list, use toggle switch in **Status** column
* Or click schedule name → Toggle "Enabled" switch in details

**When to Disable**:

* Temporary pause (e.g., during maintenance)
* Seasonal schedules (only needed certain times of year)
* Testing/debugging (disable production schedule while testing)

**Disabled Schedules**:

* ❌ Will not run automatically
* ✅ All settings and history preserved
* ✅ Can re-enable anytime without reconfiguration

### Running Schedules Manually

**"Run Now" Button**:

* Executes schedule immediately, ignoring schedule time
* Does not affect next scheduled run time
* Useful for testing or one-off manual execution

**Process**:

1. Click **"Run Now"** button next to schedule
2. Confirmation dialog appears
3. Click **"Confirm"**
4. Task executes immediately
5. New execution record created in history

**Use Cases**:

* Testing new schedule before activation
* Running report outside normal schedule
* Recovering from missed execution

### Deleting Schedules

<Warning>
  **Permanent Action**: Deleting a schedule is irreversible. All execution history will also be deleted.
</Warning>

**Steps**:

1. Click **Delete** icon (trash can) next to schedule
2. Confirmation dialog: "Are you sure you want to delete this schedule?"
3. Type schedule name to confirm (security measure)
4. Click **"Delete Permanently"**

**What Gets Deleted**:

* ✅ Schedule definition from database
* ✅ RedBeat entry from Redis
* ✅ All execution history records
* ❌ Chat sessions (preserved for reference)

**Alternative: Disable Instead**:

* If you might need the schedule later, **disable** instead of delete
* Keeps all history and settings intact

***

## Use Cases & Examples

### 1. Daily Sales Report

**Scenario**: Generate sales summary every morning at 8 AM for previous day's data.

**Configuration**:

```json theme={null}
{
  "name": "Daily Sales Report",
  "prompt": "Generate sales summary for yesterday. Include: total revenue, top products, regional breakdown.",
  "schedule_type": "DAILY",
  "schedule_config": {
    "hour": 8,
    "minute": 0
  },
  "session_config": {
    "use_existing": false
  }
}
```

**Workflow**:

1. 8:00 AM: Orchestrator receives prompt
2. Orchestrator calls SalesAnalysisAgent
3. Agent queries sales database for yesterday's data
4. Agent generates formatted report
5. Report saved to new session
6. Team opens chat session to view report

**Benefits**:

* No manual data gathering every morning
* Consistent report format
* Historical archive of daily reports in chat sessions

### 2. Weekly Team Sync Summary

**Scenario**: Every Friday at 5 PM, summarize week's activities and prepare for Monday meeting.

**Configuration**:

```json theme={null}
{
  "name": "Weekly Team Sync Summary",
  "prompt": "Summarize this week's activities: completed tasks, open issues, blockers. Format as meeting agenda.",
  "schedule_type": "WEEKLY",
  "schedule_config": {
    "day_of_week": 5,  // Friday
    "hour": 17,
    "minute": 0
  },
  "session_config": {
    "use_existing": true,
    "session_id": "weekly-sync-session-123"
  }
}
```

**Workflow**:

1. Friday 5:00 PM: Orchestrator processes prompt
2. Orchestrator calls ProjectManagementAgent
3. Agent queries GitHub, Jira, Slack for activity data
4. Agent generates meeting agenda
5. Result appended to continuous "Weekly Sync" session
6. Team reviews agenda in chat before Monday meeting

**Benefits**:

* Automatic weekly meeting preparation
* Continuous thread shows historical summaries
* Agent learns patterns over time (same session)

### 3. Real-Time Monitoring (Every 15 Minutes)

**Scenario**: Monitor website uptime and alert on issues every 15 minutes during business hours.

**Configuration**:

```json theme={null}
{
  "name": "Website Uptime Monitor",
  "prompt": "Check website status: response time, error rate, availability. Alert if any issues.",
  "schedule_type": "CRON",
  "schedule_config": {
    "minute": "*/15",   // Every 15 minutes
    "hour": "9-17",     // 9 AM to 5 PM
    "day_of_week": "1-5" // Monday to Friday
  },
  "session_config": {
    "use_existing": true,
    "session_id": "uptime-monitor-session"
  }
}
```

**Workflow**:

1. Every 15 minutes (9 AM-5 PM, Mon-Fri): Check website
2. Orchestrator calls MonitoringAgent
3. Agent makes HTTP requests to check endpoints
4. If issues detected:
   * Agent sends alert via Slack MCP
   * Agent creates Jira ticket via GitHub MCP
5. Status logged to continuous monitoring session

**Benefits**:

* Proactive issue detection
* Real-time alerts to team
* Complete monitoring history in one session

### 4. Monthly Financial Close

**Scenario**: On 1st of each month, generate financial summary for previous month.

**Configuration**:

```json theme={null}
{
  "name": "Monthly Financial Close",
  "prompt": "Generate financial summary for last month: revenue, expenses, profit margin, cash flow. Compare with previous month.",
  "schedule_type": "MONTHLY",
  "schedule_config": {
    "day_of_month": 1,
    "hour": 6,
    "minute": 0
  },
  "session_config": {
    "use_existing": false
  }
}
```

**Workflow**:

1. 1st of month, 6:00 AM: Orchestrator processes prompt
2. Orchestrator calls FinancialAnalysisAgent
3. Agent queries accounting database for previous month
4. Agent calculates metrics and trends
5. Agent generates PDF report via claude\_pdf\_processor
6. Report saved to new session
7. CFO reviews report in chat or downloads PDF

**Benefits**:

* Automated monthly close process
* Consistent financial reporting
* Early morning execution ensures reports ready for business day

### 5. Dynamic Content Curation

**Scenario**: Twice daily (8 AM, 6 PM), curate trending industry news and share with team.

**Configuration**:

```json theme={null}
{
  "name": "Industry News Curation",
  "prompt": "Find trending news in our industry. Summarize top 5 stories with key insights and implications for our business.",
  "schedule_type": "CRON",
  "schedule_config": {
    "minute": "0",
    "hour": "8,18",  // 8 AM and 6 PM
    "day_of_week": "*",
    "day_of_month": "*",
    "month_of_year": "*"
  },
  "session_config": {
    "use_existing": true,
    "session_id": "news-curation-thread"
  }
}
```

**Workflow**:

1. 8 AM & 6 PM: Orchestrator processes prompt
2. Orchestrator calls ContentCuratorAgent
3. Agent uses Firecrawl MCP to scrape industry news sites
4. Agent uses google\_search\_web to find trending topics
5. Agent summarizes top 5 stories
6. Agent posts summary to Slack via Slack MCP
7. Summary also saved to continuous news curation session

**Benefits**:

* Team stays informed without manual research
* Twice daily updates (morning and evening)
* Historical archive of curated news

***

## Troubleshooting

<AccordionGroup>
  <Accordion title="Schedule not executing at expected time" icon="clock">
    **Symptom**: Schedule is enabled but doesn't run at scheduled time

    **Possible Causes**:

    1. **Celery Worker offline**: Worker not running to pick up tasks
    2. **RedBeat not running**: Scheduler not monitoring schedules
    3. **Redis connection issue**: RedBeat can't access schedule metadata
    4. **Timezone mismatch**: Schedule configured in different timezone

    **Solution**:

    **Check System Services**:

    1. Go to Admin Dashboard → System Health
    2. Check "Celery Worker Status" (should show "Active")
    3. Check "Schedule Processor Status" (should show "Running")
    4. Check "Redis Connection" (should show "Connected")

    **Verify Schedule Registration**:

    1. Admin → Schedules
    2. Find the schedule in the list
    3. Check "Status" column shows "Enabled"
    4. Check "Last Run At" has recent timestamp

    **Timezone Consideration**:

    * All schedules use **UTC timezone** by default
    * If schedule should run at 8 AM local time (e.g., KST = UTC+9):
      * Set hour to `-1` from local (7 for 8 AM KST, which is 23 UTC previous day)
      * Or use cron with timezone awareness (future feature)
  </Accordion>

  <Accordion title="Execution fails with error" icon="exclamation-triangle">
    **Symptom**: Execution status shows FAILED in history

    **Possible Causes**:

    1. **Prompt error**: Invalid or malformed prompt
    2. **Agent not found**: Referenced agent doesn't exist
    3. **Permission issue**: Agent lacks required permissions/tools
    4. **External service down**: Tool API unavailable (Salesforce, DataLab, etc.)
    5. **Timeout**: Execution took too long

    **Solution**:

    **Check Error Message**:

    1. Go to Schedule → View History
    2. Click failed execution record
    3. Read error message in details

    **Common Errors**:

    | Error Message              | Cause                            | Solution                                    |
    | -------------------------- | -------------------------------- | ------------------------------------------- |
    | "Agent 'XYZ' not found"    | Agent deleted or renamed         | Update schedule with correct agent name     |
    | "Tool 'ABC' not available" | Agent doesn't have required tool | Add tool to agent configuration             |
    | "Timeout after 300s"       | Execution took too long          | Simplify prompt or increase timeout         |
    | "API rate limit exceeded"  | Too many API calls               | Reduce schedule frequency or batch requests |
    | "Permission denied"        | Agent lacks permissions          | Check agent tools and API keys              |

    **Test Manually**:

    1. Copy prompt from schedule
    2. Open chat with Orchestrator
    3. Paste prompt manually
    4. Observe execution and error details
    5. Fix issues before re-enabling schedule
  </Accordion>

  <Accordion title="Duplicate executions" icon="copy">
    **Symptom**: Schedule runs multiple times at same scheduled time

    **Possible Causes**:

    1. **Multiple Celery Workers**: Different workers pick up same task
    2. **RedBeat lock issue**: Distributed lock not working
    3. **Schedule duplicated**: Multiple schedules with same name

    **Solution**:

    **Identify and Remove Duplicate Schedules**:

    1. Admin → Schedules
    2. Look for schedules with the same name but different IDs
    3. Select duplicates and delete all but one
    4. Click "Save Changes"

    **Verify Schedule Lock**:

    1. Admin Dashboard → System Health
    2. Check "Schedule Locking" status (should show "Enabled")
    3. If disabled, contact support to re-enable

    **Check Worker Configuration**:

    1. Admin Dashboard → Workers
    2. Verify only 1 Celery Worker is registered (recommended for schedule processing)
    3. If multiple workers, reduce to single worker via Admin settings
  </Accordion>

  <Accordion title="Next run time not updating" icon="calendar">
    **Symptom**: `next_run_at` stays same after execution

    **Possible Causes**:

    1. **ONCE schedule**: Single execution completed, schedule disabled
    2. **Database update failure**: DB transaction failed after execution
    3. **Schedule calculation error**: Next run time calculation bug

    **Solution**:

    **Check Schedule Type**:

    * ONCE schedules: Expected behavior (automatically disabled)
    * Other types: Should update to next scheduled time

    **Re-enable Schedule to Recalculate**:

    1. Admin → Schedules
    2. Find the schedule with stale `next_run_at`
    3. Click Edit
    4. Toggle "Enabled" to OFF, then click Save
    5. Toggle "Enabled" to ON again, then click Save
    6. System automatically recalculates `next_run_at` based on schedule type

    **Need Manual Fix?**:
    If the above steps don't work, contact support with:

    * Schedule name
    * Current `next_run_at` value
    * Expected next run time
    * Support team will update schedule metadata
  </Accordion>

  <Accordion title="Cannot see execution results" icon="eye-slash">
    **Symptom**: Execution shows SUCCESS but can't find results in chat

    **Possible Causes**:

    1. **Session ID mismatch**: Results saved to unexpected session
    2. **Organization filter**: Viewing different organization's chat
    3. **Session not created**: New session creation failed

    **Solution**:

    **Find Session from Execution Record**:

    1. Admin → Schedules → View History
    2. Find successful execution
    3. Click session link → Opens exact session with results

    **Verify Session Creation**:

    1. Admin → Schedules → View History
    2. Find the execution record
    3. Check "Session ID" field (should be non-empty)
    4. If empty, execution created no session (check execution error in details)
    5. If filled, click the session link to view chat history

    **Verify Organization**:

    * Ensure you're viewing correct organization in UI
    * Use organization switcher (top right) to change if needed
    * Schedule executions only visible to same organization

    **Check Agent Logs**:

    ```bash theme={null}
    # View Orchestrator logs for session activity
    kubectl logs -n {namespace} deployment/fastapi-app --tail=100 | grep "session_id"
    ```
  </Accordion>
</AccordionGroup>

***

## Best Practices

### Schedule Design

<Check>
  **✅ DO**:

  * Use descriptive schedule names ("Daily Sales Report" not "Report1")
  * Write clear, specific prompts (avoid ambiguity)
  * Test prompts manually in chat before scheduling
  * Start with ONCE type to test, then convert to recurring
  * Use new sessions for independent tasks (reports, analysis)
  * Use existing sessions for continuous threads (monitoring, iterative analysis)
  * Set reasonable execution frequency (avoid excessive API usage)
  * Document complex schedules in schedule description
</Check>

<Warning>
  **❌ DON'T**:

  * Create too many schedules (start simple, add as needed)
  * Use extremely frequent schedules (every minute) without reason
  * Schedule long-running tasks during peak hours
  * Rely on schedules for time-critical operations (use webhooks instead)
  * Forget to monitor execution history regularly
  * Create duplicate schedules (check existing first)
  * Use ambiguous prompts that may yield unpredictable results
</Warning>

### Prompt Writing Tips

**Effective Scheduled Prompts**:

1. **Be Specific**:
   ```
   ❌ "Analyze sales"
   ✅ "Generate sales summary for yesterday: total revenue, top 10 products, regional breakdown"
   ```

2. **Include Context**:
   ```
   ❌ "Check issues"
   ✅ "Check all open support tickets tagged 'urgent'. Create priority list with customer impact assessment."
   ```

3. **Specify Output Format**:
   ```
   ❌ "Analyze data"
   ✅ "Run DataAnalysisWorkflow for sales metrics. Output as PDF and send summary via email."
   ```

4. **Use Relative Time**:
   ```
   ✅ "yesterday", "last week", "previous month" (dynamic)
   ❌ "2026-01-01" (hardcoded date, not useful for recurring schedules)
   ```

5. **Chain Actions**:
   ```
   ✅ "Analyze sales data, generate PDF report, upload to Google Drive, send notification to #sales-team Slack channel"
   ```

### Monitoring & Maintenance

**Regular Checks** (Weekly):

* Review execution history for failures
* Check success rate (aim for >95%)
* Monitor execution duration (watch for increasing times)
* Review session list for outdated sessions
* Audit schedules for relevance (disable unused)

**When to Adjust Schedules**:

* ⬆️ **Increase frequency**: If insights/reports needed sooner
* ⬇️ **Decrease frequency**: If data doesn't change often enough
* 🔄 **Change timing**: If current time causes conflicts or peak load
* ⏸️ **Disable temporarily**: During maintenance, holidays, or testing

### Security Considerations

<Warning>
  **Sensitive Data**:

  * Scheduled prompts visible to all admins in organization
  * Execution results saved to chat sessions
  * Don't include passwords, API keys, or secrets in prompts
  * Use environment variables or secure storage for credentials
</Warning>

**Access Control**:

* Only admins can create/edit/delete schedules
* Schedule executions run with creator's permissions
* Agents inherit organization's tool and MCP access
* Execution results visible to all organization members (via chat)

**Audit Trail**:

* All schedule creations/modifications logged
* Execution history preserved (start time, end time, status)
* Session links provide full conversation history
* Review audit logs regularly for unusual activity

***

## Advanced Configuration

### Conditional Scheduling (Workaround)

**Goal**: Run schedule only if certain condition met (e.g., only if new data available).

**Approach**: Use agent instruction to check condition first.

**Example Prompt**:

```
Check if new sales data available for yesterday. If yes, generate report. If no, skip execution and respond "No new data."
```

**Agent Logic**:

* Agent checks data source
* If data exists: Proceeds with analysis
* If no data: Returns early with "No new data" message
* Execution still recorded (SUCCESS status) but no actual work done

**Alternative**: Use webhook-triggered execution instead of time-based schedule (future feature).

### Multi-Organization Schedules

**Challenge**: Run same schedule across multiple organizations.

**Current Limitation**: Schedules are organization-scoped, not global.

**Workaround**:

1. Create schedule in Organization A
2. Export schedule configuration (copy JSON)
3. Switch to Organization B
4. Create new schedule with same configuration
5. Repeat for other organizations

**Future Feature**: Template-based schedule deployment for multi-org.

### Scheduled Workflows with Sub-Agents

**Use Case**: Schedule complex workflow involving multiple agents.

**Example**:

```json theme={null}
{
  "name": "Complete Customer Analysis Workflow",
  "prompt": "Run full customer analysis: 1) Search customer in CRM, 2) Get sales data, 3) Analyze engagement metrics, 4) Generate insights report, 5) Send email summary.",
  "schedule_type": "WEEKLY",
  "schedule_config": {
    "day_of_week": 1,
    "hour": 9,
    "minute": 0
  }
}
```

**Orchestrator handles**:

* Routing to appropriate sub-agents (Sequential workflow)
* Passing context between agents
* Error handling for each step
* Final result aggregation

**Benefits**:

* Single schedule triggers entire workflow
* Orchestrator manages complexity
* Results appear in one chat session

***

## Performance & Scalability

### Schedule Limits

**Recommended Limits** (per organization):

| Schedule Type       | Recommended Max | Notes                         |
| ------------------- | --------------- | ----------------------------- |
| **CRON (frequent)** | 10              | Every minute/15 minutes       |
| **DAILY**           | 50              | Once per day                  |
| **WEEKLY**          | 20              | Once per week                 |
| **MONTHLY**         | 10              | Once per month                |
| **ONCE**            | Unlimited       | Auto-disabled after execution |

**Why Limits Matter**:

* Celery Worker has finite capacity
* Concurrent executions may slow down system
* Redis storage grows with more schedules
* Database queries increase with execution history

### Optimization Tips

<Check>
  **Performance Best Practices**:

  * Stagger schedules (avoid all at 8:00 AM, spread across minutes)
  * Use longer intervals for non-critical schedules
  * Clean up old execution history periodically
  * Disable unused schedules instead of deleting (can re-enable)
  * Monitor Celery Worker resource usage
  * Use CRON wisely (avoid excessive frequency)
</Check>

**Staggering Example**:

```
❌ Bad:
- Report A: Daily at 8:00 AM
- Report B: Daily at 8:00 AM
- Report C: Daily at 8:00 AM
All compete for resources simultaneously

✅ Good:
- Report A: Daily at 8:00 AM
- Report B: Daily at 8:05 AM
- Report C: Daily at 8:10 AM
Spread across time, smooth execution
```

### Monitoring Celery Health

**Check Worker Status via Admin UI**:

1. Admin Dashboard → System Health
2. View "Active Workers" section showing worker count and status
3. View "Registered Tasks" count
4. View "Worker Memory Usage" graphs

**Monitor System Resources**:

1. Admin Dashboard → Metrics
2. Check "Cache Memory Usage" (Redis)
3. Check "Queue Size" showing pending schedules
4. Check "Execution Success Rate" showing schedule health

**Data Maintenance**:

To manage execution history or need detailed execution reports, contact support with:

* Date range
* Schedule name (optional)
* Type of report needed (execution history, timeline, resource usage)

***

## What's Next?

<CardGroup cols={2}>
  <Card title="Tools Overview" icon="wrench" href="/guides/tools/overview">
    Learn about tools that agents can use
  </Card>

  <Card title="RAG Setup" icon="database" href="/guides/tools/rag">
    Upload documents for agent knowledge
  </Card>
</CardGroup>

***

## Additional Resources

* **Celery Documentation**: [docs.celeryproject.org](https://docs.celeryproject.org/)
* **RedBeat Scheduler**: [redbeat.readthedocs.io](https://redbeat.readthedocs.io/)
* **Cron Expression Generator**: [crontab.guru](https://crontab.guru/)
* **Junis API Reference**: [api.junis.ai/docs](https://api.junis.ai/docs)

<Note>
  **Support**: For scheduling issues, contact Junis support at [contact@junis.ai](mailto:contact@junis.ai).
</Note>
