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

Open Beginner friendly
#6,710 1 comment 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

Nobody has claimed this yet.

Assessment

Difficulty
2/5
Estimated time
1-3 hours
Newbie friendliness
82/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Active
Tech stack
python
Domain
backend

Research direction

Read praisonai/scheduler/async_agent_scheduler.py around _run_schedule (390–423) and start() (252–256), then check ScheduleTicker.is_due in shared.py (85–92). Trace the first interval iteration after run_immediately=True and use the reproduction script in the issue to verify the fix. Done means startup produces one execution, with later executions following the requested interval.

Written by the indexing model from the issue text.

Description

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 ---
Dominant language
Python
Stars
9.3k
Forks
1.5k
Avg merge
1d 5h
Merged PRs (30d)
520

Getting set up

This project ships no dev container, Dockerfile or contributing guide, so setting up is up to you: start from its README, and see our first-contribution guide for the general steps.

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from MervinPraison/PraisonAI

All issues in MervinPraison/PraisonAI

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.