PraisonAI icon indicating copy to clipboard operation
PraisonAI copied to clipboard

AsyncAgentScheduler Quick Start (run_immediately=True) runs the agent twice at start

Open FurkhanShaikh opened this issue 2 weeks ago • 1 comments

Description

The AsyncAgentScheduler Quick Start starts the scheduler with

await scheduler.start("hourly", max_retries=3, run_immediately=True)

and expects one run now and the next in an hour. The agent runs twice at start: once inside start() (run_immediately), and again as soon as the background loop's first iteration begins.

For an interval schedule such as "hourly", _run_schedule (praisonai/scheduler/async_agent_scheduler.py, 390–423) sleeps only for cron schedules before running (if ticker.is_cron and not ticker.is_due()), so its first iteration runs at once, right after the immediate run in start() (252–256). ScheduleTicker.is_due (shared.py 85–92) returns True for interval schedules.

For a job with side effects (a payment, an email, a post), every scheduler start, including every process restart, runs it twice.

Environment

Python SDK, praisonai 4.8.0 with praisonaiagents 1.8.0. Provider: OpenAI-compatible, played by a local fake endpoint (no API key). Python 3.13 on Windows 11.

Reproduction

Re-checked on 2026-11-19 against praisonai 4.8.0 and praisonaiagents 1.8.0, the current releases: same result, two executions at start. The output below and the line numbers above are from 4.8.0.

Self-contained script below (pip install praisonai==4.8.0, then python repro.py). No API key; nothing leaves 127.0.0.1. It is the Quick Start's agent and start(...) call, pointed at a local fake OpenAI endpoint that counts requests.

Output:

praisonai 4.8.0, praisonaiagents 1.8.0
model requests in the first 20 s: 2, at [2.3, 2.3] s after start()
stats: {'is_running': False, 'total_executions': 2, 'successful_executions': 2, 'failed_executions': 0, 'success_rate': 100.0, 'total_cost_usd': 0.0, 'remaining_budget': 1.0, 'runtime_seconds': 22.332849, 'cost_per_execution': 0.0, 'delivered_deliveries': 0, 'undelivered_deliveries': 0}

Expected

One execution at start with run_immediately=True, then one per interval.

Suggestion

After an immediate run, have the interval loop sleep one interval before its first iteration (for example, skip the first iteration when ticker.last_run_at was just set by start()).

repro.py
# --- repro.py (verbatim) ---
"""PraisonAI AsyncAgentScheduler: the Quick Start's `start("hourly", max_retries=3,
run_immediately=True)` runs the agent twice at start, not once.

`pip install praisonai==4.7.11` then `python repro.py`. No API key; nothing leaves
127.0.0.1. The agent is the Quick Start's, pointed at a local fake OpenAI endpoint
that answers every request and counts them. Nothing in PraisonAI is patched.
"""

import asyncio
import json
import os
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

REQUESTS: list = []


class FakeOpenAI(BaseHTTPRequestHandler):
    def do_POST(self):  # noqa: N802
        json.loads(self.rfile.read(int(self.headers["Content-Length"])))
        REQUESTS.append(time.time())
        data = json.dumps({"id": "x", "object": "chat.completion", "created": 0, "model": "gpt-4o-mini",
                           "choices": [{"index": 0, "finish_reason": "stop",
                                        "message": {"role": "assistant", "content": "- one\n- two\n- three"}}],
                           "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}}).encode()
        self.send_response(200)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(data)))
        self.end_headers()
        self.wfile.write(data)

    def log_message(self, *args):
        pass


server = ThreadingHTTPServer(("127.0.0.1", 8982), FakeOpenAI)
server.daemon_threads = True
threading.Thread(target=server.serve_forever, daemon=True).start()
os.environ.update(OPENAI_API_KEY="placeholder-not-a-key", OPENAI_BASE_URL="http://127.0.0.1:8982/v1")

from importlib.metadata import version  # noqa: E402

from praisonai.scheduler import AsyncAgentScheduler  # noqa: E402
from praisonaiagents import Agent  # noqa: E402


async def main():
    agent = Agent(name="NewsChecker", instructions="Summarise today's AI news in 3 bullet points.",
                  llm="gpt-4o-mini")
    scheduler = AsyncAgentScheduler(agent, task="Check the latest AI news")
    t0 = time.time()
    await scheduler.start("hourly", max_retries=3, run_immediately=True)
    await asyncio.sleep(20)  # well inside the first hour
    await scheduler.stop()
    print(f"model requests in the first 20 s: {len(REQUESTS)}, at "
          f"{[round(t - t0, 1) for t in REQUESTS]} s after start()", flush=True)
    print(f"stats: {await scheduler.get_stats()}", flush=True)


print(f"praisonai {version('praisonai')}, praisonaiagents {version('praisonaiagents')}", flush=True)
asyncio.run(main())
# --- end repro.py ---

FurkhanShaikh avatar Nov 19 '26 23:11 FurkhanShaikh

👋 Thanks for opening this issue, @FurkhanShaikh!

A maintainer will review this shortly. In the meantime:

Bug and enhancement reports are auto-triaged with Claude. Questions and other issues: a maintainer can comment @claude to trigger analysis.

Routing: Agent-callable tools → PraisonAI-Tools; lifecycle plugins (tracing/hooks/guardrails) → PraisonAI-Plugins. TypeScript/JavaScript SDK fixes land in src/praisonai-ts/ in this repo.