Triggering Your AI Agent on a Schedule with Cron Jobs: Building True Autonomous Behavior

Triggering Your AI Agent on a Schedule with Cron Jobs: Building True Autonomous Behavior

Z
Zahid Hasan Tonmoy
November 25, 2026
14 min read
🇧🇩 বাংলায় পড়ুন
|
0 views
Audio Overview & Podcast
~1 min quick overview
0%

Triggering Your AI Agent on a Schedule with Cron Jobs: Building True Autonomous Behavior
Triggering Your AI Agent on a Schedule with Cron Jobs: Building True Autonomous Behavior

Triggering Your AI Agent on a Schedule with Cron Jobs: Building True Autonomous Behavior

In our previous guide on connecting your AI agent to Telegram and WhatsApp with production webhooks, we built an acknowledge-first webhook pipeline so developers can message DevPulse from their phones. While adding Telegram and WhatsApp made our agent much easier to reach, look closely at how it still behaves: whether a user types a question in our Next.js web UI or sends a message on Telegram, the agent sits completely idle until a human pokes it first. A system that only wakes up when spoken to is reactive, not truly autonomous.

To give an AI agent proactive, time-driven autonomy, you trigger its reasoning loop via scheduled Cron Jobs—using either Vercel Cron (vercel.json + a CRON_SECRET-guarded Next.js Route Handler) or an asynchronous Python scheduler (APScheduler inside FastAPI) backed by an atomic Redis distributed lock (SET ... NX EX) and a database watermark cursor. This architecture allows your agent to wake up on a strict schedule (such as every morning at 08:00 UTC or every 30 minutes), scan for new untriaged GitHub issues, cross-reference internal pgvector documentation, log structured ticket drafts in Supabase, and push a proactive summary to your team's Telegram channel only when actionable anomalies are found.

Today, in Post 33 of our 62-part series, we transform DevPulse from a purely reactive chat responder into a scheduled, self-directed background agent.

Reactive Agents vs. Proactive Scheduled Agents

Back in Post 11, when we mapped out the levels of AI agent autonomy, we noted that moving from Level 2 (human-triggered tool execution) to Level 3 (conditional autonomous monitoring) requires removing the human prompt as the sole trigger. Consider what happens inside a software engineering team overnight:

  • At 02:15 AM, three users report HTTP 429 token-refresh failures on GitHub.
  • With a Reactive Agent: Those bug reports sit unread until an engineer logs in at 09:30 AM, copies the issue URLs, and manually asks the agent to triage them.
  • With a Cron-Triggered Autonomous Agent: At 08:00 AM sharp, a cron trigger wakes up DevPulse. The agent queries GitHub for issues created since its last run watermark, searches Supabase pgvector for matching rate-limit docs, drafts a consolidated triage report in PostgreSQL, and posts a single actionable morning briefing to your engineering Telegram group.

Running an agent unattended at 08:00 AM, however, introduces three engineering hazards that do not exist in interactive chat:

  1. Multi-Worker Duplicate Execution: In Post 31, we configured our Dockerized Python FastAPI server to run with --workers 2 for concurrency. If you attach an in-memory cron scheduler directly to the FastAPI app startup without a distributed lock, both Uvicorn worker processes will fire the 08:00 AM cron job at the exact same millisecond—burning double the LLM tokens and sending duplicate alerts.
  2. Re-Processing the Same Data Every Cycle (Missing Watermarks): If your cron job runs every hour and asks the agent to 'triage open GitHub issues', a stateless cron job will re-triage the exact same 10 open issues every single hour, wasting thousands of tokens on unchanged data.
  3. Unauthenticated Public Cron Routes: Because serverless cron jobs work by sending an HTTP GET request to a route like /api/cron/daily-triage, leaving that route without bearer token verification allows any external bot to trigger expensive background agent runs at will.

3D glassmorphism visualization of a precision orbital clock ring triggering an AI agent core through a Redis lock gate and watermark filter prism
3D glassmorphism visualization of a precision orbital clock ring triggering an AI agent core through a Redis lock gate and watermark filter prism

The Autonomous Cron Execution Architecture

To make scheduled agent runs safe, idempotent, and cost-controlled, every cron execution must pass through a four-stage pipeline before calling OpenAI or Anthropic:

mermaid graph TD A[Cron Scheduler Trigger: 08:00 UTC / Every 30m] --> B{1. Verify CRON_SECRET Header} B -->|Unauthorized| C[Reject with HTTP 401] B -->|Verified| D{2. Acquire Redis Distributed Lock: SETNX} D -->|Lock Held by Another Worker| E[Skip Duplicate Run & Return 200 OK] D -->|Lock Acquired| F{3. Check Unprocessed Delta / Watermark} F -->|Zero New Issues Since Last Run| G[Skip LLM Call: Spend 0 Tokens] F -->|New Issues Found| H[4. Run Bounded Autonomous Agent Loop: maxSteps 4] H --> I[Save Triage Report in Supabase & Update Watermark] I --> J[Push Proactive Digest to Telegram Channel] Architecture Flow Summary: Cron Scheduler Trigger → CRON_SECRET Auth Check → Redis Distributed Lock (SETNX) → Delta Watermark Pre-Check (Zero-Token Short-Circuit) → Bounded Multi-Step Agent Loop → Supabase State Update & Outbound Telegram Digest.

Look closely at Stage 3 (Check Unprocessed Delta / Watermark) in the diagram above. This is one of the most important cost-saving patterns in production AI engineering: never wake up an LLM just to check if there is work to do. Use a fast, deterministic database or API check first; only invoke the LLM when new, unprocessed items actually exist.

Zahid's Engineering Perspective: The Morning Two Uvicorn Workers Sent Twin Triage Digests

When I first added an automated morning triage schedule to our Dockerized Python FastAPI service on my Ubuntu VPS, I used APScheduler's AsyncIOScheduler inside FastAPI's lifespan handler. When I tested it locally on my laptop with uvicorn main:app --reload (which runs a single worker process), the job fired once and worked cleanly.

Then I deployed the container to my VPS using the production Dockerfile from Post 31, which starts Uvicorn with --workers 2. The next morning at 08:00:00 UTC, my phone buzzed twice at the exact same second with two nearly identical Telegram triage digests—and my Anthropic dashboard showed two parallel 4-step Claude 3.5 Sonnet runs!

Why did that happen? When Uvicorn boots with --workers 2, it forks two independent Python processes, and both processes execute the FastAPI lifespan startup hook—meaning two separate AsyncIOScheduler instances were ticking in memory inside the same container. Adding a 5-line atomic Redis lock (await redis.set('devpulse:cron:morning_triage', 'locked', nx=True, ex=1800)) at the start of the job function ensured that Worker 1 acquired the lock in 0.2 milliseconds while Worker 2 saw False and exited immediately without touching the LLM.

Step 1: Creating the Cron State & Watermark Table in Supabase

To ensure our scheduled agent never re-analyzes the same GitHub issue twice and records an audit log of every autonomous run, run this SQL migration in your Supabase SQL Editor:

`sql -- supabase/migrations/20261125_agent_cron_runs.sql create table if not exists public.agent_cron_state ( job_name text primary key, last_processed_issue_number int not null default 0, last_run_at timestamptz not null default now(), last_status text not null default 'idle' );

create table if not exists public.agent_cron_logs ( id uuid primary key default gen_random_uuid(), job_name text not null, new_items_count int not null default 0, summary_output text not null default '', prompt_tokens int not null default 0, completion_tokens int not null default 0, duration_ms int not null default 0, created_at timestamptz not null default now() );

insert into public.agent_cron_state (job_name, last_processed_issue_number) values ('github-issue-triage', 400) on conflict (job_name) do nothing; `

Step 2: Building a Serverless Cron Route in Next.js (/api/cron/triage/route.ts)

If your agent is hosted on Vercel (from Post 30), Vercel Cron triggers a scheduled GET request to your specified route and automatically injects an Authorization: Bearer <CRON_SECRET> header using the CRON_SECRET environment variable from your project settings.

First, add the crons schedule block to your vercel.json file (for example, 0 8 * * * to run every day at 08:00 UTC):

typescript // Add to vercel.json in your Next.js project root: // 'crons': [ // { // 'path': '/api/cron/triage', // 'schedule': '0 8 * * *' // } // ]

Now create src/app/api/cron/triage/route.ts. Notice how this handler verifies CRON_SECRET, checks if there are any new GitHub issues above last_processed_issue_number before calling the LLM, runs a bounded autonomous loop, updates the watermark in Supabase, and pushes the digest to Telegram:

`typescript // src/app/api/cron/triage/route.ts import { NextRequest, NextResponse } from 'next/server'; import { generateText } from 'ai'; import { createAnthropic } from '@ai-sdk/anthropic'; import { createClient } from '@supabase/supabase-js'; import { defaultDevPulseConfig } from '@/lib/agent/blueprint'; import { devPulseTools } from '@/lib/agent/vercel-tools'; import { getVerifiedServerEnv } from '@/lib/agent/env-check';

export const runtime = 'nodejs'; export const dynamic = 'force-dynamic'; export const maxDuration = 60;

interface GitHubIssueSummary { number: number; title: string; state: string; html_url: string; }

async function fetchNewGitHubIssuesSince( repo: string, minIssueNumber: number ): Promise<GitHubIssueSummary[]> { const response = await fetch( https://api.github.com/repos/${repo}/issues?state=open&per_page=5&sort=created&direction=desc, { headers: { Accept: 'application/vnd.github+json', 'User-Agent': 'DevPulse-Autonomous-Cron/1.0', }, signal: AbortSignal.timeout(5000), } );

if (!response.ok) return []; const rawList = (await response.json()) as GitHubIssueSummary[]; return rawList.filter((item) => item.number > minIssueNumber); }

export async function GET(req: NextRequest) { const startTime = Date.now(); const authHeader = req.headers.get('authorization'); const cronSecret = process.env.CRON_SECRET;

if (!cronSecret || authHeader !== Bearer ${cronSecret}) { return NextResponse.json({ error: 'Unauthorized cron trigger.' }, { status: 401 }); }

const env = getVerifiedServerEnv(); const supabase = createClient(env.SUPABASE_URL, env.SUPABASE_SERVICE_ROLE_KEY, { auth: { persistSession: false, autoRefreshToken: false }, });

const { data: stateRow } = await supabase .from('agent_cron_state') .select('last_processed_issue_number') .eq('job_name', 'github-issue-triage') .single();

const lastWatermark = stateRow?.last_processed_issue_number ?? 0; const newIssues = await fetchNewGitHubIssuesSince('vercel/ai', lastWatermark);

// Zero-Token Short-Circuit: Do not call the LLM if nothing new happened! if (newIssues.length === 0) { await supabase .from('agent_cron_state') .update({ last_run_at: new Date().toISOString(), last_status: 'no_new_items' }) .eq('job_name', 'github-issue-triage');

return NextResponse.json({
  ok: true,
  status: 'skipped_zero_new_issues',
  watermark: lastWatermark,
  durationMs: Date.now() - startTime,
});

}

const highestIssueNumber = Math.max(...newIssues.map((i) => i.number)); const issueListPrompt = newIssues .map((i) => #${i.number}: ${i.title}) .join(' | ');

const anthropic = createAnthropic({ apiKey: env.ANTHROPIC_API_KEY });

const autonomousPrompt = [ You are running in unattended Autonomous Cron Mode for repository vercel/ai., New open issues detected since last watermark (#${lastWatermark}): ${issueListPrompt}., 1. Inspect the most critical issue using inspectLiveGitHubIssue., 2. Cross-reference our internal documentation using searchKnowledgeBase., 3. Write a concise 3-bullet morning engineering triage briefing., ].join(' ');

const result = await generateText({ model: anthropic('claude-3-5-sonnet-latest'), system: defaultDevPulseConfig.systemPrompt, prompt: autonomousPrompt, tools: devPulseTools, maxSteps: 4, temperature: 0.1, });

await supabase .from('agent_cron_state') .update({ last_processed_issue_number: highestIssueNumber, last_run_at: new Date().toISOString(), last_status: 'completed', }) .eq('job_name', 'github-issue-triage');

await supabase.from('agent_cron_logs').insert({ job_name: 'github-issue-triage', new_items_count: newIssues.length, summary_output: result.text, prompt_tokens: result.usage.promptTokens, completion_tokens: result.usage.completionTokens, duration_ms: Date.now() - startTime, });

const botToken = process.env.TELEGRAM_BOT_TOKEN; const alertChatId = process.env.TELEGRAM_ALERT_CHAT_ID;

if (botToken && alertChatId) { await fetch(https://api.telegram.org/bot${botToken}/sendMessage, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ chat_id: alertChatId, text: [Autonomous Triage Digest]\n\n${result.text.slice(0, 3500)}, }), }); }

return NextResponse.json({ ok: true, status: 'completed', processedCount: newIssues.length, newWatermark: highestIssueNumber, durationMs: Date.now() - startTime, }); } `

Step 3: Running Autonomous Cron Jobs on Your Docker VPS with Python APScheduler and Redis Locks

What if you are self-hosting your agent on a Linux VPS with Docker (from Post 31) and want your Python FastAPI service to run scheduled autonomous checks every 30 minutes without external cloud triggers?

Install apscheduler in your Python environment (pip install apscheduler) and create agent/scheduler.py. Notice how we use an atomic Redis lock (nx=True, ex=1500) so even if you scale Uvicorn to 4 workers, only one worker executes the autonomous loop:

`python

agent/scheduler.py

import os import time from contextlib import asynccontextmanager import httpx import redis.asyncio as aioredis from apscheduler.schedulers.asyncio import AsyncIOScheduler from apscheduler.triggers.cron import CronTrigger from fastapi import FastAPI from agent.runner import run_devpulse_python_agent

REDIS_URL = os.environ.get('REDIS_URL', 'redis://localhost:6379/0') redis_client = aioredis.from_url(REDIS_URL, decode_responses=True)

async def run_scheduled_autonomous_triage() -> None: lock_key = 'devpulse:cron:lock:autonomous_triage' # Acquire distributed lock for 25 minutes (1500s) so sibling workers skip acquired = await redis_client.set(lock_key, 'locked', nx=True, ex=1500) if not acquired: return

last_issue_str = await redis_client.get('devpulse:cron:watermark:issue_num')
last_watermark = int(last_issue_str) if last_issue_str else 400

async with httpx.AsyncClient(timeout=5.0) as client:
    resp = await client.get(
        'https://api.github.com/repos/vercel/ai/issues?state=open&per_page=3',
        headers={'User-Agent': 'DevPulse-Python-Cron/1.0'},
    )
    if resp.status_code != 200:
        return
    issues = resp.json()

new_issues = [
     item for item in issues if int(item.get('number', 0)) > last_watermark
]

if not new_issues:
    return

highest_num = max(int(i['number']) for i in new_issues)
issue_summary = ', '.join(f"#{i['number']} ({i['title'][:60]})" for i in new_issues)

goal = (
    f'Autonomous scheduled check detected new open issues: {issue_summary}. '
    f'Inspect the highest priority issue, check internal docs, and write a brief triage report.'
)

result = run_devpulse_python_agent(user_prompt=goal, max_steps=4)
await redis_client.set('devpulse:cron:watermark:issue_num', str(highest_num))

bot_token = os.environ.get('TELEGRAM_BOT_TOKEN')
chat_id = os.environ.get('TELEGRAM_ALERT_CHAT_ID')
if bot_token and chat_id and result.success:
    async with httpx.AsyncClient(timeout=10.0) as client:
        await client.post(
            f'https://api.telegram.org/bot{bot_token}/sendMessage',
            json={
                'chat_id': int(chat_id),
                'text': f'[VPS Autonomous Cron Report]\n\n{result.final_answer[:3500]}',
            },
        )

scheduler = AsyncIOScheduler(timezone='UTC')

@asynccontextmanager async def lifespan_with_scheduler(app: FastAPI): scheduler.add_job( run_scheduled_autonomous_triage, trigger=CronTrigger(minute='0,30'), id='autonomous_triage_30m', replace_existing=True, max_instances=1, coalesce=True, ) scheduler.start() try: yield finally: scheduler.shutdown(wait=False) `

To activate the scheduler in main.py, simply pass lifespan=lifespan_with_scheduler into FastAPI(title='DevPulse Python Agent API', lifespan=lifespan_with_scheduler). Look at the two safety flags on scheduler.add_job: max_instances=1 (prevents overlapping runs in the same process) and coalesce=True (if the server was briefly paused across two missed intervals, it combines them into a single catch-up run instead of firing a burst).

Dark frosted glass multi-worker scene showing a central Redis lock crystal allowing one worker to run the scheduled agent while deflecting a duplicate worker
Dark frosted glass multi-worker scene showing a central Redis lock crystal allowing one worker to run the scheduled agent while deflecting a duplicate worker

Common Mistakes When Running AI Agents on Cron Schedules

Before leaving an autonomous agent running overnight on a schedule, verify that your implementation avoids these 4 expensive anti-patterns:

  1. Calling the LLM Before Checking if New Data Exists: If your cron job runs every 15 minutes (96 times a day) and invokes GPT-4o or Claude 3.5 Sonnet just to ask 'Are there any new bugs?', you will pay for 96 multi-step agent runs every single day even when your repository had zero activity! Always perform a cheap deterministic check (comparing issue.number > lastWatermark) first, and return early with 0 tokens spent when nothing changed.
  2. Running In-Memory Schedulers Across Multiple Workers Without a Distributed Lock: Whenever you run gunicorn or uvicorn --workers 2+ (or multiple Docker containers), every worker starts its own copy of AsyncIOScheduler. Always gate scheduled jobs with an atomic Redis SET lock_key 'locked' NX EX <ttl> check.
  3. **Leaving the /api/cron/* Endpoint Publicly Callable Without CRON_SECRET**: Never deploy a cron Route Handler without checking req.headers.get('authorization') === 'Bearer ' + process.env.CRON_SECRET. An unprotected cron route is an open invitation for crawlers and bots to trigger background LLM loops.
  4. Giving Unattended Cron Agents Level 4 Destructive Write Permissions: Because no human is watching a cron job at 03:00 AM, never give a scheduled agent unrestricted tools that delete database rows, close customer tickets, or push code directly to main. Keep cron agents at Level 2/3 Autonomy: allow them to read docs, analyze logs, draft tickets in a staging table, and send proactive notifications to your team.

Frequently Asked Questions

What is the difference between Vercel Cron and running APScheduler on a Docker VPS?

Vercel Cron is an external HTTP scheduler managed by Vercel that sends a GET request to your Next.js route on a schedule; on the free Hobby plan, Vercel Cron jobs are limited to running once per day, and each invocation is capped by your serverless maxDuration (60s). On a self-hosted Docker VPS (Post 31), APScheduler with Redis locks lets you run jobs every 5 or 15 minutes with no execution time limits for $0 extra cost.

How do I test my /api/cron/triage route locally without waiting until 08:00 AM?

Because our Next.js cron endpoint is a standard GET Route Handler protected by a Bearer token, you can trigger it anytime on localhost:3000 using curl -H 'Authorization: Bearer your-local-cron-secret' http://localhost:3000/api/cron/triage to verify the watermark check, Supabase logging, and Telegram alert delivery immediately.

How do we keep Redis session state and cached tool results fast across both interactive and cron agent runs?

In this post and Post 32, we used Redis for webhook deduplication and distributed cron locks. In the very next post (Post 34), we will expand our Redis layer into a full Session Memory and Semantic Tool Cache so repeated documentation and GitHub queries return in under 2 milliseconds without hitting upstream APIs.

🟢 Available for Freelance & Contract Work

Need a High-Performance Web App or Custom AI Solution?

I help founders, businesses, and engineering teams build lightning-fast web applications, resilient backend architectures, and intelligent AI workflows. Have an idea in mind? Let’s bring it to life.

Fast MVP Launch (2–4 weeks)
AI Agent & LLM API Integration
100/100 Core Web Vitals & SEO
Production-Ready Clean Architecture

Found this article helpful?

Give some claps to support more in-depth engineering logs!

0 views
Z

Zahid Hasan Tonmoy

Author & Developer

MERN Full Stack Developer & AI Agent Developer based in Dhaka, Bangladesh. Writing about web development, React, PostgreSQL and my learning journey.

Related Articles

Stay Updated

Subscribe to get insights on full-stack architecture, AI agent engineering, and web development.