# Add a Scheduled Job to a Flask App with RQ

Yes. An agent adds a recurring RQ job using the worker's built-in scheduler, a CLI command to start it and a test, proves it runs and opens a pull request.

[Run this on Rush](https://cloud.getrush.ai/run/add-scheduled-job/rq/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads how background work is already wired. In a Flask app like miguelgrinberg/microblog, `app/__init__.py` builds `app.redis = Redis.from_url(app.config['REDIS_URL'])` and `app.task_queue = rq.Queue('microblog-tasks', connection=app.redis)`, and `requirements.txt` pins `rq==1.15.1`, `redis==5.0.1`, `Flask==3.0.0` and `Flask-Mail`. `app/tasks.py` creates its own app with `create_app()` and pushes a context at import, then defines `export_posts(user_id)`, which reports progress through `_set_task_progress` and sends the result with `send_email(..., sync=True)`. `User.launch_task` in `app/models.py` enqueues `app.tasks.<name>` and records a `Task` row, and `deployment/supervisor/microblog-tasks.conf` runs the worker as `rq worker microblog-tasks`. `app/cli.py` registers a `translate` command group on a blueprint, `User.unread_message_count()` counts messages newer than `last_message_read_time`, and `tests.py` runs `unittest` on an in-memory SQLite `TestConfig` with `ELASTICSEARCH_URL = None`. Nothing in the app runs on a timer.

RQ 1.15 has a scheduler inside the worker: `rq worker --with-scheduler` checks the queue's `ScheduledJobRegistry` once a second, and `queue.enqueue_at` or `enqueue_in` places a job there. Interval repeats (`Repeat`) arrived in RQ 2.2, so with the pinned version a recurring job re-enqueues itself. The agent writes `send_unread_digest()` in `app/tasks.py`: for each user with unread messages it renders new `email/unread_digest.txt` and `.html` templates and sends them with `send_email`, then in a `finally` block enqueues the next run with `app.task_queue.enqueue_in(timedelta(days=1), 'app.tasks.send_unread_digest', job_id='unread-digest')`, so one failed send never ends the series, and the fixed `job_id` means a second schedule replaces the first rather than doubling it. A `reschedule` parameter lets a test run the body alone.

Operators get commands rather than a shell session. `app/cli.py` gains a `digest` group: `flask digest schedule` enqueues the first run at the next hour named by a new `DIGEST_HOUR_UTC` config value, and `flask digest status` reads `ScheduledJobRegistry(queue=app.task_queue)` and prints when the next run is due. `deployment/supervisor/microblog-tasks.conf` changes its command to `rq worker --with-scheduler microblog-tasks`, and the README's deployment section gets the two commands. Nothing changes for `export_posts` or the `Task` rows, which belong to per-user work.

A `DigestCase` in `tests.py` creates two users and a message between them, calls `send_unread_digest(reschedule=False)` inside `mail.record_messages()`, and asserts one message to the recipient and none to the sender; `TESTING` keeps Flask-Mail from sending. For the live proof the sandbox has no Docker, so the agent installs `redis-server` with `apt-get`, starts `rq worker --with-scheduler microblog-tasks` in the background, enqueues the digest with `enqueue_in(timedelta(seconds=10), ...)` from `flask shell`, and shows the worker log running it and `flask digest status` reporting the next run a day out. `python tests.py` runs the whole file last.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Add a daily unread-messages digest as a scheduled RQ job. The pinned rq is 1.15.1, which has the worker's built-in scheduler but no Repeat, so write send_unread_digest in app/tasks.py to email each user with unread messages (new email/unread_digest templates) and then re-enqueue itself one day later in a finally block with a fixed job_id, with a reschedule flag a test can turn off. Add a flask digest command group with schedule (first run at DIGEST_HOUR_UTC from config) and status (reads ScheduledJobRegistry). Change the supervisor worker command to use --with-scheduler and document the commands in the README. Add a unittest case using mail.record_messages. Prove it: install Redis, run the worker with the scheduler, enqueue the digest ten seconds out, show the worker running it and status showing the next run. Run python tests.py. Open a pull request quoting the worker log and the test output.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

The pull request changes `app/tasks.py`, `app/cli.py`, `config.py`, `deployment/supervisor/microblog-tasks.conf`, `README.md` and `tests.py`, and adds the two digest templates under `app/templates/email/`. Its description quotes the worker log lines for the enqueued digest and its re-enqueue, the `flask digest status` output, and the `unittest` summary.

A reviewer checks that the re-enqueue sits in `finally` so an SMTP failure does not end the series, that the `job_id` is fixed, and that the digest query uses `unread_message_count` rather than a new definition of unread. The transcript at GET /o/{org}/sessions/{id}/messages has the Redis install, the worker output and the test run in full.

Nothing is scheduled on your servers by the run. After the deploy, `flask digest schedule` once on the host starts the series, and the `--with-scheduler` worker carries it from there.

## Run it on every new recurring task

A weekly cleanup of expired tokens, a nightly recount, a reminder mail: each is this job again with another function. Send POST /o/{org}/sessions with a prompt naming the function and its interval, and the agent writes it in the same shape beside the digest, with a `request_id` that is a UUID v5 of the task name so a retried send returns the run it already started.

A webhook URL on the API key delivers `run.completed` when each run finishes, with the `session_url` to read its pull request from, so the next task's branch is ready to review without polling.

## Why run it on Rush?

A scheduled job is only believable once it has fired from a real worker and put the next run back in the registry, and that means Redis, a worker process and a wait, which is exactly the kind of setup that gets skipped on a laptop. The sandbox runs Redis and the scheduler-enabled worker for the length of the run, and the worker's own log lines are in the transcript.

The digest, the cleanup and the reminder are separate runs on separate branches, each with its own worker log, so a reviewer reads one job per pull request and the same two commands in every description.

## Frequently asked questions

### Why not rq-scheduler or a cron entry?

rq-scheduler is another package and another process to supervise, and the worker already has a scheduler at this version. A cron entry would work but lives outside the app's deployment files and needs the app's environment on the host. Re-enqueueing inside the worker keeps one process and one config file.

### What if the worker is down when the job is due?

The job waits in `ScheduledJobRegistry` and runs when a worker with `--with-scheduler` comes back, then schedules the next one a day from that run. Upgrading to RQ 2.2 or later would allow `Repeat` with a fixed interval instead; say so in the prompt and the agent writes it that way.

### Can two workers double-send?

No. Only one scheduler is active per queue, and the fixed `job_id` means a second `enqueue_in` for the same id replaces the pending job rather than adding one. The `flask digest status` command shows a single next run.

### Does the test need Redis?

No. The test calls the digest body with `reschedule=False`, so it never touches the queue, and `TESTING` makes Flask-Mail record messages instead of sending. Only the live proof in the sandbox uses Redis.

## More RQ jobs

- [Add Retries with Backoff to RQ Jobs](https://getrush.ai/run/add-task-retries/rq/)
- [Upgrade RQ 1.x to RQ 3 in a Flask App](https://getrush.ai/run/upgrade-rq/rq/)
- [Add Job Timeouts to a Flask RQ App](https://getrush.ai/run/add-job-timeouts/rq/)

## The same job on other stacks

- [Add a Scheduled Job to a Medusa Backend](https://getrush.ai/run/add-scheduled-job/medusa/)

## More jobs like this: Hand off a long task

- [Add Scheduled Messages to a Slack Bolt App](https://getrush.ai/run/add-scheduled-messages/slack-bolt/)
- [Add a Schedule to a Dagster Project](https://getrush.ai/run/add-schedules/dagster/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
