# Add a Scheduled Job to a Vapor App

Yes. An agent adds Vapor Queues with the Redis driver, a nightly AsyncScheduledJob that purges old todos, a migration, tests on the test driver, and opens a PR.

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

## What the agent does

The agent reads the service before it schedules anything in it. In an app generated from vapor/template with Fluent, `Package.swift` declares `swift-tools-version:6.3`, pins `vapor` from 4.121.4, `fluent` from 4.13.0, one Fluent driver (`fluent-postgres-driver` 2.12.0, `fluent-mysql-driver` 4.8.0 or `fluent-sqlite-driver` 4.9.0, whichever `manifest.yml` offered at generation) and `swift-nio` from 2.101.0, and turns on upcoming features such as `ExistentialAny` and `MemberImportVisibility` for both targets. `Sources/App/Models/Todo.swift` is a `final class Todo: Model, @unchecked Sendable` with schema `todos`, an `@ID` and one `@Field(key: "title")`; `Migrations/CreateTodo.swift` creates that table with `.id()` and a required string; `configure.swift` registers the database from `DATABASE_HOST`, `DATABASE_PORT`, `DATABASE_USERNAME`, `DATABASE_PASSWORD` and `DATABASE_NAME` and adds `CreateTodo()` to `app.migrations`; `entrypoint.swift` calls `configure(app)` and then `app.execute()`. Nothing in the project runs on a timer, and there is no `created_at` column to decide what is old.

The job needs that column first. The agent adds `@Timestamp(key: "created_at", on: .create) var createdAt: Date?` to `Todo`, so Fluent fills it on insert, and writes `Migrations/AddTodoCreatedAt.swift`, an `AsyncMigration` whose `prepare` calls `database.schema("todos").field("created_at", .datetime).update()` and whose `revert` calls `deleteField("created_at")`, registered after `CreateTodo()` so a database that already ran the first migration moves forward with the `migrate --yes` command the `migrate` service in `docker-compose.yml` runs. `TodoDTO` gains an optional `createdAt`, copied in `toDTO()`, so a client can see the value the purge will use.

Then the queue. Vapor's documentation says to depend on the driver rather than on `queues` itself, so `Package.swift` gets `.package(url: "https://github.com/vapor/queues-redis-driver.git", from: "1.0.0")` and the executable target gets `.product(name: "QueuesRedisDriver", package: "queues-redis-driver")`. `Jobs/PurgeOldTodosJob.swift` conforms to `AsyncScheduledJob`; its `run(context:)` deletes every `Todo` whose `createdAt` is older than a retention read from `TODO_RETENTION_DAYS` (default 30) through `context.application.db`, and logs the count it removed. In `configure.swift` the agent calls `try app.queues.use(.redis(url: Environment.get("REDIS_URL") ?? "redis://localhost:6379"))`, registers `app.queues.schedule(PurgeOldTodosJob()).daily().at(.midnight)`, and calls `try app.queues.startScheduledJobs()` so the schedule runs inside the `serve` process, because the documentation requires scheduled jobs to be set up before the application boots. The pull request names the alternative, `swift run <App> queues --scheduled` as its own process, for a deployment that runs several `app` replicas, since in-process scheduling would fire the purge once per replica. `docker-compose.yml` gains a `redis` service on the official image and `REDIS_URL: redis://redis:6379` in the shared environment block, and `app` depends on it.

Tests stay on the template's Swift Testing suite and its `withApp` helper. Under `.testing` the agent swaps the driver for the one `XCTQueues` ships, `app.queues.use(.asyncTest)`, so `swift test` needs no Redis, and adds two cases: one creates two todos, backdates one by setting `createdAt` to forty days ago and saving it again (the `.create` trigger does not overwrite a value on update), calls `PurgeOldTodosJob().run(context:)` with the queue's context and asserts `Todo.query(on: app.db).count()` is one and the survivor is the recent row; the other runs the job against two fresh rows and asserts nothing is deleted. It runs `swift build` and `swift test` on the `swift:6.3-noble` image the template's `Dockerfile` and `test-template.yml` use, then `docker compose up redis` and `swift run` with `REDIS_URL` set to confirm the app boots with the schedule registered, and keeps every output.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add a nightly scheduled job to this Vapor app with Vapor Queues and open a pull request. Read Package.swift, Sources/App/configure.swift, routes.swift, entrypoint.swift, Models/Todo.swift, Migrations/CreateTodo.swift, DTOs/TodoDTO.swift, Controllers/TodoController.swift, Tests/AppTests/AppTests.swift, Dockerfile and docker-compose.yml first. Add a @Timestamp(key: \"created_at\", on: .create) property to Todo with an AsyncMigration that adds a nullable created_at datetime field, registered after CreateTodo, and expose createdAt on TodoDTO. Add queues-redis-driver to Package.swift. Write Jobs/PurgeOldTodosJob.swift as an AsyncScheduledJob that deletes todos older than TODO_RETENTION_DAYS days (default 30) and logs the count. In configure.swift use the redis driver from REDIS_URL, schedule the job daily at midnight, and call startScheduledJobs so it runs inside serve; in the test environment use the asyncTest driver from XCTQueues instead. Add a redis service and REDIS_URL to docker-compose.yml. Add Swift Testing cases that back-date one of two todos, run the job directly and check only the old one is removed, and that fresh rows survive. Run swift build and swift test, start redis with docker compose and boot the app once with REDIS_URL set, and paste the output in the pull request. Explain when to run queues --scheduled as a separate process instead. Do not change CreateTodo or the existing routes.",
  "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

What comes back is a pull request that edits `Package.swift`, `configure.swift`, `Models/Todo.swift`, `DTOs/TodoDTO.swift`, `docker-compose.yml` and `Tests/AppTests/AppTests.swift`, and adds `Migrations/AddTodoCreatedAt.swift` and `Jobs/PurgeOldTodosJob.swift`. The description shows the schedule line, names `TODO_RETENTION_DAYS` and `REDIS_URL` with their defaults, pastes the `swift test` output with the two new cases named, and explains the one deployment decision it could not make: in-process scheduling for a single `app` container, or `queues --scheduled` as its own service when there are several.

The run's record keeps every command with its output: the package resolution that pulled `queues-redis-driver`, `swift build`, each `swift test`, the `docker compose up redis` and the boot with `REDIS_URL` set. A repository with a workflow that runs `swift test` on pull requests runs the new cases on the `swift:6.3-noble` image before anyone reviews; the template itself ships without one, so the pasted output is the check.

A reviewer checks that the migration is appended after `CreateTodo`, that rows with a null `created_at` (anything inserted before the migration) are left alone, that `.at(.midnight)` is the hour they want in the server's timezone, and whether the purge should be a soft delete instead. Then they merge, run the migration and deploy.

## Run it on every new Vapor service

A developer starts this from the terminal when a service built from the template needs its first background job: one `POST /o/{org}/sessions` with the repository in `resources` and this prompt. The run clones the service into its own sandbox, adds the column, the driver, the job and the tests, and opens the pull request; a follow-up through `POST /o/{org}/sessions/{id}/messages` wakes the parked sandbox to change the retention rule or add a second job on the same queue.

Give the key a `webhook_url` and `run.completed` arrives with `data.session_url` when the turn ends, so the pull request link lands in your tooling without polling. Several services can get a job at once, each in its own sandbox, up to the key's `max_concurrent`.

## Why run it on Rush?

A scheduled job is the code path nobody watches run: it fires at midnight, in production, against a Redis the laptop does not have. In a Rush sandbox the agent compiles the package with the pinned Swift 6.3 toolchain, runs the job directly in a test with the queue's own test driver, starts a real Redis with Compose and boots the app against it, and keeps every command and its output in the run's record beside the pull request, so a reviewer reads a purge that removed one backdated row out of two rather than a promise that it would.

The change touches four layers at once, the model, a migration, the queue configuration and Compose, and the order matters for a database that already exists. The agent does the four in one pass with the tests that pin them, and the same request works unchanged on the next Vapor service that needs a nightly job.

## Frequently asked questions

### Why does the job need a created_at column?

The template's `Todo` has only an id and a title, so there is nothing to say which rows are old. A `@Timestamp` with `on: .create` is filled by Fluent on insert and left alone on update, which is also what lets the test backdate a row by saving it again.

### Do the tests need Redis?

No. Under `.testing` the app uses the `asyncTest` driver from the `XCTQueues` library that ships with the `queues` package, and the test calls the job's `run(context:)` directly. Redis is only started for the manual boot the agent does with Compose.

### What happens if I run two app containers?

With `startScheduledJobs()` in `configure.swift`, each process keeps its own schedule and the purge runs once per container. For that deployment the pull request describes running `queues --scheduled` as a single separate service and removing the in-process call.

### Will it delete the todos that already exist?

Rows inserted before the migration have a null `created_at` and the query filters on `createdAt < cutoff`, so they are not matched. The pull request says so; a reviewer who wants them purged backfills the column first.

## More Vapor jobs

- [Add File Uploads to a Vapor API](https://getrush.ai/run/add-file-uploads/vapor/)
- [Set Up GitHub Actions CI for a Vapor App](https://getrush.ai/run/add-github-actions-ci/vapor/)
- [Add Health Checks to a Vapor App](https://getrush.ai/run/add-health-checks/vapor/)

## The same job on other stacks

- [Schedule Database Jobs With pg_cron on Supabase](https://getrush.ai/run/add-cron-jobs/supabase/)

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

- [Add a Cron Trigger to a Cloudflare Worker](https://getrush.ai/run/add-cron-trigger/cloudflare-workers/)
- [Add a Cron Trigger to a Hono Worker](https://getrush.ai/run/add-cron-trigger/hono/)

## 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/)
