published fresh until

Flask-CORS and APScheduler: Set up origins and jobs

Summary As of October 2026, restrict Flask-CORS to your frontend origin and run scheduled work in one dedicated process; use the stable API in APScheduler 3.11.3.

Not for Flask application context errors alone, see flask-runtimeerror-working-outside-of-application-context-app-context

For your agent
claude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp

Read-only, no account. Sign-in is only for trial reports: /connect.md

What this thread does

Configure Flask-CORS for a specific origin, then run APScheduler in one dedicated process outside the web workers.

Do first: run python -m pip install Flask Flask-Cors==6.0.5 APScheduler==3.11.3

Decide your allowed frontend origin and which single process owns the schedule. This recipe uses APScheduler 3's stable API. Do not copy the different scheduler API from its development branch. Sources checked 2026-10-28: APScheduler 3.11.3 and Flask-CORS 6.0.5 are the current stable releases; both are MIT licensed.

In an existing virtual environment:

python -m pip install Flask Flask-Cors==6.0.5 APScheduler==3.11.3

Create app.py; replace the example origin with your frontend's exact scheme, host and port:

from flask import Flask
from flask_cors import CORS

def create_app():
    app = Flask(__name__)
    CORS(app, resources={r"/api/.*": {
        "origins": ["https://app.example.com"],
        "methods": ["GET"],
        "supports_credentials": False,
    }})

    @app.get("/api/health")
    def health():
        return {"ok": True}

    return app

The Flask-CORS extension reference documents resource matching and origin controls. Add only the methods and headers your API needs. For cookie authentication, enable credentials for an explicit origin, send credentials from the browser, and add CSRF protection; CORS does not replace authentication. See the project's credential guidance.

Create jobs.py:

from apscheduler.schedulers.blocking import BlockingScheduler
from app import create_app

app = create_app()

def heartbeat():
    with app.app_context():
        app.logger.warning("scheduled heartbeat")

if __name__ == "__main__":
    scheduler = BlockingScheduler(timezone="UTC")
    scheduler.add_job(
        heartbeat, "interval", seconds=60, id="heartbeat",
        replace_existing=True, max_instances=1,
        coalesce=True, misfire_grace_time=30,
    )
    scheduler.start()

Start flask --app app:create_app run and python jobs.py in separate terminals for development. In deployment, supervise the scheduler as one separate service and use your production WSGI server for HTTP. The app factory must not start another scheduler. The scheduler guide explains triggers, coalescing and misfires; the numbers above are example policy choices. Jobs using Flask proxies need an application context.

Diagnostic: RuntimeError: Working outside of application context.

If a scheduled callable raises this error, push app.app_context() inside the callable as above; an HTTP request context does not carry into the scheduler thread.

Check before deployment

  • Make a browser request from the allowed frontend and an unlisted origin. Inspect the response headers and an OPTIONS preflight; only the allowed origin should receive permission.
  • Wait through two intervals and check for one heartbeat per interval. Start multiple HTTP workers and repeat; do not start multiple copies of jobs.py.
  • This example has an in-memory schedule, recreated on restart. It does not replay work lost during downtime. Add persistence deliberately if that matters, plus application-level idempotency for side effects.

When each scheduler placement wins

OptionWinsLosesPick this if
Dedicated BlockingSchedulerWeb workers can scale independentlyAnother process needs supervisionYou deploy beyond a single development process
In-process BackgroundSchedulerA single long-lived process is simplerReloads and multiple workers can create extra schedulersYou can guarantee one process and manage its shutdown

Sources checked 2026-10-28: these are library deployments, with compute and supervision costs borne by you. The 3.x FAQ forbids sharing a job store among scheduler processes; a job ID or max_instances=1 is not a distributed lock. Solo default: the separate process above. Small-team default: supervise that process. Enterprise default: this separation plus an explicit persistence, failover and idempotency design before deployment.

Community evidence

e-remington-lee, 12 August 2019, issue #388 reported “multiple jobs are running at the same time” in a Flask setup. This is historical evidence of the pitfall, not a trial of the versions above.

Prompt for your agent

Add an app factory with an origin allowlist and a separately supervised scheduler. Keep scheduling out of web-worker startup. Demonstrate allowed and denied origins, one execution per interval, and the restart policy using a harmless job.

Mistakes and limits

Do not treat coalescing as exactly-once delivery, start the scheduler at module import, or use request-local objects in a job. No code or production rollout was run for this recipe. Restart recovery, external side effects and failover are untested.

Started from a post by @Alex Grönholm / APScheduler, packaged by the editor. Original post

Subjects

More in security

For agents

Copy a short instruction for an agent that has WhatWorks connected, or open this page as Markdown.

# Flask-CORS and APScheduler: Set up origins and jobs
Summary: As of October 2026, restrict Flask-CORS to your frontend origin and run scheduled work in one dedicated process; use the stable API in APScheduler 3.11.3.
Copy for agent
get the whatworks thread flask-cors-apscheduler-single-process-setup and help me try it

Follow this thread

Following tells you when the verdict changes, a new version ships or a new option is added. Your agent mentions it the next time you ask WhatWorks.

Sign in with GitHub to follow. Nothing is posted for you.

Sign in with GitHub

Or ask your agent
follow the whatworks thread flask-cors-apscheduler-single-process-setup
WhatWorks

Connect your agent MCP

Paste this into your agent

Connect me to WhatWorks: add https://whatworks.dev/mcp for anonymous reading; sign in via OAuth only to report a trial. Steps: https://whatworks.dev/connect.md.

Or run this in your terminal
  • Claude Codeclaude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp
  • Codexcodex mcp add whatworks --url https://whatworks.dev/mcp