Agent Scheduling Patterns

Production-grade guide to agent scheduling patterns covering architecture patterns, implementation strategies, testing approaches, and operational best practices for enterprise engineering teams.

Agent scheduling patterns address how AI agents are invoked, repeated, and coordinated over time. This matters when agents need to run on a cadence, respond to external events, or coordinate across distributed instances without human intervention. Poor scheduling leads to missed runs, overlapping executions, resource contention, or silent failures that only surface during incident review.

Periodic Scheduling

Periodic scheduling is the most common pattern for agents that must execute at regular intervals. Three widely available mechanisms are cron, systemd timers, and Kubernetes CronJobs. Each has different semantics for drift, concurrency, and deadline handling.

Cron (crontab)

Cron remains the simplest approach for single-host deployments. A crontab entry consists of five time fields, a command, and optional environment variables.

# Run an agent every day at 02:15 UTC
15 2 * * * /usr/local/bin/agent-runner --agent-id 42 --output /var/log/agent-42.log

To list existing entries:

crontab -l

To edit:

crontab -e

Sharp edges: Cron does not track execution state. If a run takes longer than the interval, multiple instances overlap. Cron also relies on the host clock; drift or daylight‑saving transitions can shift runs without immediate notice. Output is mailed to the local user unless redirected, which can cause log loss in containerized or headless environments.

systemd Timers

systemd timers provide a more robust alternative, especially on servers where the system manager is already running. A timer unit can define a calendar schedule, a monotonic schedule, or a boot‑time delay. The associated service unit contains the actual agent invocation.

timer unit (agent-schedule.timer):

[Unit]
Description=Run agent 42 daily

[Timer]
OnCalendar=*-*-* 02:15:00 UTC
Persistent=true

[Install]
WantedBy=timers.target

service unit (agent-schedule.service):

[Unit]
Description=Agent 42 execution

[Service]
Type=oneshot
ExecStart=/usr/local/bin/agent-runner --agent-id 42 --output /var/log/agent-42.log

To start and enable:

systemctl start agent-schedule.timer
systemctl enable --now agent-schedule.timer

To inspect state and last runs:

systemctl list-timers --all
journalctl -u agent-schedule.service --no-pager -n 30

Flags and keys: OnCalendar accepts calendar specifiers (*-*-* 02:15:00 UTC) and monotonic timers (--sleep 86400). Persistent=true ensures that if the machine is off at the scheduled time, the timer fires as soon as the system boots. OnCalendar= respects the system timezone unless UTC is appended; omitting the timezone indicator defaults to the system locale, which is a frequent source of mis‑scheduled runs.

Sharp edges: A timer may show active while the underlying service fails silently if ExecStart returns a non‑zero exit code that systemd does not treat as fatal (e.g., if Restart=no is set). Persistent=true combined with a missing Persistent=true on the service unit can cause missed runs after reboot. Additionally, OnCalendar expressions do not support per‑minute granularity with step values (e.g., */5) in all systemd versions; verify version compatibility.

Kubernetes CronJobs

For containerized workloads, a CronJob native to Kubernetes declaratively schedules agent execution across a cluster. The schedule field uses a cron-like format, and several sub‑fields control concurrency and deadline behavior.

CronJob manifest:

apiVersion: batch/v1
kind: CronJob
metadata:
  name: agent-42
spec:
  schedule: "15 2 * * *"
  concurrencyPolicy: Forbid
  startingDeadlineSeconds: 3600
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: agent
            image: myregistry/agent-runner:latest
            args: ["--agent-id", "42", "--output", "/log/agent-42.log"]
          restartPolicy: OnFailure

Commands:

kubectl create -f agent-42-cronjob.yaml
kubectl get cronjob agent-42
kubectl describe cronjob agent-42

Flags and keys: concurrencyPolicy accepts Allow, Forbid, or Replace. Forbid prevents overlapping runs if a previous job has not completed; Replace terminates the previous job and starts a new one. startingDeadlineSeconds defines how far past the scheduled time a CronJob may still start; beyond this threshold, the job is dropped and counted as missed. SuccessfulJobsHistoryLimit and FailedJobsHistoryLimit control how many completed/failed records are retained.

Sharp edges: If concurrencyPolicy is set to Allow, multiple instances of the agent may run simultaneously, which can cause race conditions on shared state or resources. startingDeadlineSeconds is often misunderstood: a value of 0 means the job starts immediately if the pod is available, but if the cluster is under heavy load, the job may be indefinitely postponed. Omitting startingDeadlineSeconds defaults to 0 in most Kubernetes distributions, which can lead to silent back‑pressure failures when the API server or scheduler is throttled. Label selectors and pod security policies may also block the runner container if not pre‑configured, resulting in a PodScheduled condition that never transitions to Running without clear error messaging in the dashboard.

Event‑Driven & Trigger‑Based Scheduling

Not all agent execution follows a fixed cadence. Event‑driven patterns respond to external stimuli—webhook callbacks, message queue entries, or API polls—making them suitable for asynchronous workflows, user‑initiated actions, or systems where the cadence is unpredictable.

Webhook Trigger Pattern

Many platforms expose an HTTP endpoint that, when called, enqueues or directly executes an agent. The caller is responsible for idempotency and authentication.

curl example initiating an agent run:

curl -X POST https://api.example.com/agents/42/run \
  -H "Authorization: Bearer $API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"reason": "manual-trigger"}'

Typical successful response:

{
  "runId": "run-abc123",
  "status": "queued",
  "scheduledAt": "2026-02-10T02:15:00Z"
}

Sharp edges: If the webhook endpoint returns 202 Accepted but the agent runner does not persist the request (e.g., due to a downstream queue overflow), the caller has no immediate feedback. Retrying the webhook may create duplicate runs if the receiver is not idempotent. Some platforms include a X-Run-Id header in the response; correlating this with logs is essential for audit trails. TLS certificate expiry on the webhook URL is a common silent failure mode: the agent scheduler may silently drop calls if the client does not validate the server certificate or if the certificate chain is incomplete.

Polling with Backoff

When a webhook is unavailable, a polling loop checks an API endpoint at a controlled rate. This pattern is common in on‑premise or legacy integrations.

bash polling loop with exponential backoff:

#!/usr/bin/env bash
AGENT_ID=42
MAX_RETRIES=5
INITIAL_INTERVAL=10  # seconds

for (( attempt=1; attempt<=MAX_RETRIES; attempt++ )); do
  response=$(curl -s -o /dev/null -w "%{http_code}" \
    -H "Authorization: Bearer $API_TOKEN" \
    "https://api.example.com/agents/${AGENT_ID}/status")
  
  if [[ "$response" == "200" ]]; then
    echo "Agent ${AGENT_ID} is ready. Triggering run..."
    curl -X POST "https://api.example.com/agents/${AGENT_ID}/run" \
      -H "Authorization: Bearer $API_TOKEN" \
      -d '{}'
    exit 0
  fi
  
  echo "Attempt ${attempt}: status ${response}. Backing off..."
  backoff=$(( INITIAL_INTERVAL * 2 ** (attempt - 1) ))
  sleep "$backoff"
done

echo "Failed to trigger agent after ${MAX_RETRIES} attempts." >&2
exit 1

Sharp edges: Fixed‑interval polling wastes bandwidth and can trigger rate‑limit counters. Exponential backoff reduces load but does not eliminate the risk of thundering herd if many agents poll simultaneously after a restart. A 429 Too Many Requests response is often returned with a Retry-After header; failing to parse and respect this header can result in immediate further throttling or temporary blacklisting of the client IP. Some APIs return 204 No Content when the agent is already running; not handling this idempotently may cause repeated trigger attempts.

Conditional & Dependency‑Aware Scheduling

Agents often depend on prior state— a predecessor agent must succeed, a file must exist, a database row must have a specific status, or a feature flag must be enabled. Scheduling logic should encode these guards before dispatching a run.

State‑Store Validation (SQL)

When agent state is stored in a relational database, a query can determine whether the preconditions are met before scheduling.

psql query checking predecessor completion:

SELECT status, updated_at 
FROM agent_run 
WHERE agent_id = 42 
  AND parent_run_id = 'run-xyz789' 
ORDER BY updated_at DESC 
LIMIT 1;

Typical output if the predecessor succeeded:

 status |     updated_at
--------+-----------------------
 done   | 2026-02-10 02:10:12+00

If the predecessor is still running or failed, the row will show running or failed respectively, or no row will exist if the predecessor has not yet been recorded.

Integration in a scheduler script:

status=$(psql -t -A -F '|' -h db-host -U app_user -d agent_db \
  -c "SELECT status FROM agent_run WHERE agent_id = 42 AND parent_run_id = 'run-xyz789' ORDER BY updated_at DESC LIMIT 1;")

if [[ "$status" == "done" ]]; then
  curl -X POST https://api.example.com/agents/42/run \
    -H "Authorization: Bearer $API_TOKEN"
else
  echo "Predecessor not done (status: $status). Skipping schedule."
fi

Sharp edges: psql -t -A strips headers, but null results (no row returned) can appear as an empty string, which may not equal the literal string "done". Always check for empty output explicitly. Transaction isolation levels may cause a newly completed run to not be visible in the same session; a READ COMMITTED or REPEATABLE READ level is typically required for accurate state checks. Connection pooling timeouts or unreachable database endpoints will cause the scheduler to fail silently if error output is redirected to /dev/null.

API‑Based Guard Check

When state resides in a remote service, a GET request can validate conditions before triggering.

curl guard check:

curl -s -H "Authorization: Bearer $API_TOKEN" \
  "https://api.example.com/agents/42/guard?check=predecessor" \
  | jq -r '.ready'

Typical JSON response:

{
  "ready": true,
  "reason": "predecessor completed successfully",
  "details": {
    "parentRunId": "run-xyz789",
    "completedAt": "2026-02-10T02:10:12Z"
  }
}

If ready is false, the scheduler logs the reason and defers the run.

Sharp edges: JSON parsing errors (e.g., missing jq, malformed response from the API) can cause the scheduler to misinterpret the guard result. Some APIs return HTTP 200 OK with an empty body or {} when the guard condition is unmet, which jq -r '.ready' would render as null rather than false. Explicitly checking the exit code of jq or using a fallback grep is advisable. Authentication tokens that have expired mid‑scheduler loop will result in 401 Unauthorized; many implementations will silently retry with a stale token if token refresh logic is not embedded in the scheduler.

Resource Constraints, Backoff, and Silent Failures

Scheduling does not exist in a vacuum. Agent execution consumes CPU, memory, disk I/O, and network bandwidth. Poorly bounded schedules are a frequent source of production incidents.

Rate Limiting and Max Concurrent Runs

Most production systems impose a cap on how many agent instances may run simultaneously, either per‑agent, per‑project, or across the entire deployment. Exceeding these limits typically results in 429, 503, or internal queue rejection.

kubectl limit‑range example (hypothetical quota):

apiVersion: v1
kind: LimitRange
metadata:
  name: agent-quota
spec:
  limits:
  - type: Container
    max:
      cpu: "2"
      memory: "1Gi"
    min:
      cpu: "100m"
      memory: "128Mi"

If a CronJob or service request attempts to instantiate a container exceeding max cpu or max memory, Kubernetes will admit the pod only if it can guarantee the request; otherwise the pod remains in Pending state indefinitely, and events are emitted to the pod's events field.

Sharp edges: A common misconception is that resources.limits prevents oversubscription at the node level, but the scheduler may still attempt to place the pod if another node has capacity, leading to unexpected distribution. Conversely, setting requests too low may allow scheduling on under‑provisioned nodes, causing the agent runtime to OOM‑kill the process mid‑execution. The kernel OOM killer does not always produce a clean exit code; the process may be terminated with signal 9, and the scheduler may report a non-zero exit code that is actually a signal termination, leading to mis‑classified failures in monitoring dashboards.

Exponential Backoff and Jitter

When an agent runner encounters a transient error (e.g., downstream API 503, network timeout, temporary lock contention), a retry policy with backoff prevents immediate re‑try and reduces load on the failing dependency.

pseudo‑code for backoff with jitter:

import time, random

def retry_with_backoff(fn, max_attempts=5, base_delay=1.0):
    for attempt in range(1, max_attempts + 1):
        try:
            return fn()
        except TransientError as e:
            if attempt == max_attempts:
                raise e
            delay = base_delay * (2 ** (attempt - 1)) + random.uniform(0, 0.5)
            time.sleep(delay)

Sharp edges: Pure exponential backoff without jitter can create synchronized retries across many instances (the “thundering herd” problem) when the dependency recovers. Adding a small random jitter term breaks synchronization but introduces non‑determinism in total completion time, which can complicate SLA calculations. Some systems interpret a Retry-After HTTP header as the authoritative delay, ignoring the computed backoff value; failing to prioritize the header can result in retries that are either too aggressive or unnecessarily delayed.

What Silently Fails

Summary

Effective agent scheduling requires matching the pattern to the operational context: cron for simple single‑host duties, systemd timers for server‑level reliability, Kubernetes CronJobs for distributed containerized workloads, and event‑driven triggers for asynchronous or user‑initiated execution. Each mechanism carries distinct sharp edges—timezone drift, concurrency conflicts, deadline semantics, state‑store visibility, and resource quotas—that only become apparent under load or after a failure. Design schedulers with explicit guards, bounded retries, and observability (exit codes, status fields, event logs) so that silent failures are caught before they cascade. Map these patterns to the tools and APIs your deployment uses, and validate each path under both nominal and stressed conditions.

This page was rewritten on 13 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at [email protected] and we will correct it.