Recurring jobs

Run Python on a schedule inside Octocom, with no cron server or hosting to maintain.

A recurring job runs your Python code on a schedule, with no conversation required. It lets Octocom take over the routine work around support. For example, a job can post a digest of open cases to Slack every morning, or sync account changes with your billing system every hour. Octocom hosts and runs the schedule, so there is nothing for you to deploy.

Recurring jobs complete the set of Python triggers:

TriggerUse
The AI agent decides to call itA custom action
Something happens (a conversation closes, a call ends, an alert fires)An event handler
A schedule, at most every five minutesA recurring job (this page)
Another system or a web page calls a URLA custom HTTP endpoint

Recurring jobs run at most every five minutes. For real-time reactions, use an event handler, a webhook or an HTTP endpoint.

Common uses:

  • Send a daily summary or digest to Slack or email
  • Reconcile data with an external system (orders, subscriptions, accounts, inventory)
  • Revisit cases saved in the organization store, such as pending cancellations
  • Post regular reports to a Google Sheet
  • Delete state you no longer need

Create jobs under Settings -> Automation -> Recurring Jobs, or ask Copilot or any MCP client to build them.

How it works

  1. You create a recurring job: a name, a business, a schedule and your Python code.
  2. The job runs automatically at each scheduled occurrence.
  3. Every run is recorded (result, stdout, stderr and failure reason) and shown in the job's run history.

A recurring job belongs to your organization and runs in the context of one business (available to your code as context["business"]).

Schedules

A schedule is a standard 5-field cron expression (minute hour day-of-month month day-of-week), evaluated in the job's timezone:

ExpressionMeaning
0 9 * * *Daily at 09:00
*/15 * * * *Every 15 minutes
0 9 * * 1Mondays at 09:00
30 7 1 * *The 1st of every month at 07:30
0 8,17 * * *Twice a day, at 08:00 and at 17:00

The timezone is an IANA name like UTC, Europe/Vilnius or America/New_York, so "daily at 9am" stays at 9am local time across daylight-saving changes.

Invalid cron expressions and unknown timezones are rejected when you save the job, with an error explaining what's wrong.

Write a recurring job

A recurring job implements a run_job function. It receives the same kind of context object as custom actions, with one difference: there is no conversation, so context["conversation"] and context["customer"] are None.

import requests

def run_job(context):
    business = context["business"]

    # Fetch something from your own API and act on it
    response = requests.get(
        "https://api.example.com/pending-orders",
        timeout=30,
    )
    pending = response.json()

    return {"business": business["slug"], "pending": len(pending)}

The job descriptor

context["job"] describes the run:

FieldDescription
idThe recurring job's ID
nameThe recurring job's name
scheduleThe cron expression
timezoneThe schedule's timezone
scheduled_forThe occurrence this run is for (ISO timestamp; None for manual runs)
last_run_atWhen the job last ran (None on the first run)
trigger"schedule" for scheduled runs, "manual" for manually triggered runs

See Python context for the full context reference.

Helper functions

Recurring jobs have access to the built-in helper library. Helpers that operate on a conversation need to be given a conversation explicitly, since a recurring job doesn't run inside one. For example, send_bot_message and close_conversation accept a conversation_id argument.

See Python helpers for the full list. Use the organization store when a job needs state shared with actions or event handlers, or a cursor that survives between runs.

Examples

Daily Slack digest

import requests

def run_job(context):
    business = context["business"]

    requests.post("https://hooks.slack.com/services/YOUR/WEBHOOK/URL", json={
        "text": f"Good morning! Daily digest for {business['name']} is ready.",
    }, timeout=10)

    return {"status": "sent"}

Schedule: 0 9 * * *, timezone Europe/Vilnius.

Weekly Google Sheets report

from datetime import datetime, timezone

def run_job(context):
    add_google_sheets_row("YOUR_SPREADSHEET_ID", {
        "Week of": datetime.now(timezone.utc).strftime("%Y-%m-%d"),
        "Business": context["business"]["slug"],
        "Status": "ok",
    })

    return {"status": "logged"}

Schedule: 0 8 * * 1 (Mondays at 08:00).

Test and run history

You can test a recurring job's code from the dashboard before it goes live:

  1. Open the recurring job in the dashboard
  2. Click Run Test in the Test Job panel
  3. The code runs once, immediately, and shows the result, stdout, and stderr

Through Copilot or MCP, test_recurring_job runs the code the same way, and run_recurring_job triggers a real, recorded run with trigger set to "manual".

Test runs are not recorded in the run history, but the Python code still runs normally. External API requests and mutating helpers such as send_bot_message and close_conversation have real effects. Add your own dry_run switch while developing jobs that send messages, issue refunds, or change external state.

Every real run (scheduled or manually triggered) is recorded. The Run History panel on the job's edit page shows recent runs with their status, duration, output and failure reason, so you can always answer "what did this job do last Tuesday". Through MCP, use list_recurring_job_executions and get_recurring_job_execution. Runs are kept for 90 days. The stored result, stdout and stderr are each cut to 32,000 characters and the failure reason to 8,000, so return a short summary rather than whole datasets.

Calling the REST API

Jobs get OCTOCOM_API_BASE_URL and OCTOCOM_ORG_API_KEY injected, so they can call the REST API without storing a key. Background automations have their own rate limits: all recurring jobs and event handlers of an organization share 1,000 requests a minute, and one job can make at most 300. Over the limit, requests return 429 with Retry-After.

A job that scans conversations should:

  • List changes with a cursor. Call GET /rest/v1/conversations with updatedSince set to the last cursor, then save the newest updatedAt you processed. Advance the cursor after every successful run, not only when something matched, or the backlog grows until the job can never catch up.
  • Read details in bulk. Fetch details with POST /rest/v1/conversations/bulk, up to 200 IDs per call, instead of one GET /rest/v1/conversations/{id} per conversation.
  • Stop on 429. Return an error status, or wait for Retry-After seconds once. Retrying immediately in a loop only gets more 429s.
  • Avoid the busiest minutes. Many jobs run on the hour and every 5 minutes. A schedule such as 3-59/10 * * * * (every 10 minutes, starting at :03) spreads the load.
import requests
from datetime import datetime, timezone

BASE = OCTOCOM_API_BASE_URL.rstrip("/")
HEADERS = {"X-API-Key": OCTOCOM_ORG_API_KEY}

def run_job(context):
    entry = organization_store_get("my_job", "cursor")
    if not entry:
        # First run: start from now instead of scanning the whole history.
        organization_store_upsert("my_job", "cursor", datetime.now(timezone.utc).isoformat())
        return {"status": "initialised"}
    cursor = entry["value"]

    # Up to 200 changes per run, oldest first; the next run continues from the cursor.
    r = requests.get(f"{BASE}/rest/v1/conversations", headers=HEADERS, timeout=30,
                     params={"updatedSince": cursor, "sortBy": "updatedAt",
                             "sortOrder": "asc", "limit": 200})
    if r.status_code == 429:
        return {"status": "rate_limited", "retry_after": r.headers.get("Retry-After")}
    r.raise_for_status()
    conversations = r.json()["data"]
    if not conversations:
        return {"status": "ok", "scanned": 0}

    details = requests.post(f"{BASE}/rest/v1/conversations/bulk", headers=HEADERS, timeout=60,
                            json={"ids": [c["id"] for c in conversations]})
    details.raise_for_status()
    for conversation in details.json()["data"]:
        ...  # your check

    organization_store_upsert("my_job", "cursor", conversations[-1]["updatedAt"])
    return {"status": "ok", "scanned": len(conversations)}

Limits and reliability

LimitValue
Minimum interval5 minutes. Schedules with occurrences closer together are rejected
Elapsed time per run5 minutes, including time waiting for HTTP requests
CPU time per run30 seconds of active computation; network waits don't count
Active jobs per organization100
Consecutive failures10 failed runs in a row deactivate the job
Run history90 days; result, stdout and stderr cut to 32,000 characters each, failure reason to 8,000
REST API callsShared with event handlers: 1,000 a minute per organization, 300 per job
  • Late pickup skips stale occurrences. If a job is picked up late, it runs once and then waits for the next future occurrence. It never fires a backlog of missed runs in a burst. Occurrences stay aligned to the cron grid; use context["job"]["scheduled_for"] if your code needs to know which occurrence it's running for.
  • Overlapping runs are skipped. Scheduled and manual runs of the same job never overlap. An overlapping attempt is recorded as skipped and does not reset the failure counter. After an interrupted run, the job can stay locked for up to six minutes. Different jobs can still run at the same time. Keep external effects idempotent, because a timeout does not prove that an external action stopped.
  • Repeated failures pause the job. After 10 failed runs in a row, the job is deactivated so a broken script doesn't keep running. Editing or re-enabling the job resets the failure counter.

Manage jobs with Copilot or MCP

ToolPurpose
list_recurring_jobs, get_recurring_jobFind jobs and read their code and schedule
create_recurring_job, update_recurring_jobCreate or change a job
test_recurring_jobRun the code once without recording it
run_recurring_jobTrigger a real, recorded run now
list_recurring_job_executions, get_recurring_job_executionRead the run history
list_recurring_job_versions, restore_recurring_job_versionRead the change history and restore a version
archive_recurring_job, list_archived_recurring_jobsArchive a job and find archived ones

Best practices

  • Be idempotent. Design jobs so that running twice for the same period produces the same result. A late pickup or a manual run alongside a scheduled one shouldn't double-post or double-charge anything.
  • Don't assume every occurrence ran. If your job processes "everything since the last run", derive the window from your own data (e.g. a "last processed" marker in the external system) rather than from the schedule.
  • Handle errors gracefully. If an external API is down, catch the exception and return an error status. Failures are recorded in the run history either way, but a clean error message is easier to debug, and uncaught exceptions count toward automatic deactivation.
  • Keep runs under the 5-minute elapsed-time limit and 30-second CPU budget. Batch or paginate work; if one run can't finish the whole task, make the job resumable so the next occurrence continues where it left off.
  • Stay inside the REST API budget. All recurring jobs and event handlers of an organization share 1,000 REST requests a minute, and any one of them can make at most 300. Helpers such as the organization store count too. See Calling the REST API.
  • Watch the run history after changes. After creating or editing a job, check its next run's output in the Run History panel to confirm it behaves as expected.

On this page