All jobs

Add a Scheduled Job to a Medusa Backend

Yes. An agent adds a cron job under src/jobs of your Medusa backend that flags abandoned carts through a workflow, with a unit test, and opens a PR.

Run this on RushOpens the console with this prompt ready to send, in a Project that has your repository.

What the agent does

The agent reads the backend before it writes a job. In a monorepo laid out like medusajs/dtc-starter, apps/backend/src/jobs/ holds only a README, which documents the shape Medusa expects: a default export that takes the MedusaContainer, and a config export with a unique name, a cron schedule and an optional numberOfExecutions. src/subscribers/ and src/workflows/ are README-only too. medusa-config.ts sets databaseUrl and the http block and nothing else: no modules, no workerMode. package.json pins every @medusajs/* package at 2.22.2 and requires Node 22.23.4 or newer; jest.config.js picks a suite by TEST_TYPE, with unit tests matched at src/**/__tests__/**/*.unit.spec.ts and HTTP integration tests under integration-tests/http/. The root AGENTS.md points events and cron at src/subscribers/ and src/jobs/, and says business logic belongs in workflows.

The job the agent writes is src/jobs/flag-abandoned-carts.ts, scheduled with 0 * * * *. It resolves the logger and Query from the container (ContainerRegistrationKeys.LOGGER and ContainerRegistrationKeys.QUERY), then calls query.graph on the cart entity for id, email, metadata and updated_at, filtered to carts whose updated_at is older than 24 hours, whose completed_at is null and whose email is set, reading them 100 at a time with skip and take until a page comes back short. Carts that already carry metadata.abandoned_at are skipped, so a cart is flagged once however many times the job runs.

The write goes through a workflow rather than a module service, as AGENTS.md asks. src/workflows/flag-abandoned-carts.ts is built with createWorkflow from @medusajs/framework/workflows-sdk; it takes the cart ids, uses transform to shape them into one update per cart, and calls updateCartsStep from @medusajs/medusa/core-flows to set metadata.abandoned_at to an ISO timestamp, returning the count. The job logs that count at info. Keeping the write in a workflow means the follow-up most stores want, an email through the Notification Module, becomes one more step in the same file; the backend has no notification provider in medusa-config.ts today, so the pull request names that as the next change instead of adding a provider nobody configured.

Checking the job means running it. The agent adds src/jobs/__tests__/flag-abandoned-carts.unit.spec.ts, which hands the job a stub container whose resolve returns a fake query.graph and a logger, mocks the workflow module with jest.mock, and asserts which cart ids reach the workflow: the stale cart with an email, not the completed one, not the one already flagged. pnpm run test:unit from apps/backend runs it under TEST_TYPE=unit. Then it installs Postgres in its sandbox, runs pnpm install, pnpm exec medusa db:migrate and medusa develop with the schedule temporarily set to every minute, as the Medusa docs suggest for trying a job, reads the info line with the count in the boot log, restores the hourly schedule, and runs pnpm run lint, which is medusa lint, before opening the pull request.

Start it with one API call

POST https://api.phoenix.so/o/{org}/sessions with this body:

{
  "agent": "claude",
  "input": "Add a scheduled job to this Medusa backend that flags abandoned carts. Read AGENTS.md, apps/backend/medusa-config.ts, apps/backend/package.json, apps/backend/jest.config.js, apps/backend/integration-tests/setup.js and the README files in apps/backend/src/jobs, src/workflows and src/subscribers first. Create apps/backend/src/jobs/flag-abandoned-carts.ts with config name flag-abandoned-carts and schedule 0 * * * *. In the job resolve the logger and Query from the container, read carts with query.graph (fields id, email, metadata, updated_at) where updated_at is older than 24 hours, completed_at is null and email is set, 100 at a time, skip carts whose metadata.abandoned_at is already set, and run a workflow in apps/backend/src/workflows/flag-abandoned-carts.ts that uses updateCartsStep from @medusajs/medusa/core-flows to set metadata.abandoned_at to an ISO timestamp; log the count. Add a unit test under src/jobs/__tests__ matching the jest unit pattern, with a stub container and a mocked workflow. Install Postgres in the sandbox, run the migrations, start medusa develop with the schedule set to every minute to confirm the job runs and logs, restore the hourly schedule, run pnpm run test:unit and pnpm run lint, then open a pull request that quotes the log line and the test output and notes that a deployment with workerMode set to server runs no scheduled jobs.",
  "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 adds apps/backend/src/jobs/flag-abandoned-carts.ts, apps/backend/src/workflows/flag-abandoned-carts.ts and apps/backend/src/jobs/__tests__/flag-abandoned-carts.unit.spec.ts, and adds one row to the table in AGENTS.md so the next agent finds the job. Its description states the schedule, the three conditions a cart must meet, the metadata key it writes, and quotes the info line from the sandbox boot log and the pnpm run test:unit summary.

It also says what the job does not do: it sends no email and deletes nothing, and it explains the one deployment fact that decides whether the job runs at all. Medusa runs scheduled jobs in the worker; a backend started with workerMode set to server has no worker, so production needs a worker or shared instance beside the server, which .env.template in this starter does not mention yet.

Before merging, a reviewer settles the cutoff (24 hours is the pull request's choice), the metadata key the storefront will read, and whether the cron minute should avoid the hour when the store is busiest. If a notification provider is added later, the email becomes a second step in the same workflow.

Run it on every Linear issue labelled jobs

An automation on the Project with a linear trigger on linear.issue.labeled, jobs in config.labels, and the prompt 'this issue describes work the backend should do on a schedule; add a job under apps/backend/src/jobs with a cron expression, put the logic in a workflow under src/workflows, add a unit test with a stub container, run it once locally, and open a pull request' starts one run per labelled issue. The trigger adds the issue after the prompt and fills in nothing else, so a request for a nightly inventory report and a request for a weekly cleanup each get their own job file.

A team that runs several stores from this starter sends this body once per repository from its own server, each POST /o/{org}/sessions with that repository in resources and a request_id that is a UUID v5 of the repository's full name, so a retried call returns the run already started. Each run reads its own backend: a store that already registers a notification provider in medusa-config.ts gets the email step as well.

The use case this job follows, with its automation and trigger: Hand off a long task.

Why run it on Rush?

A Medusa job is a few lines, and the mistakes sit around them: a config export left in place after the function is removed breaks the build, a query without pagination loads every cart, a job that writes through a module service skips the workflow layer the project standardises on, and a deployment with only a server instance never runs the job. The agent fits the job to this backend's conventions and runs it against a real Postgres in its sandbox, which a laptop without a local database cannot do quickly.

The boot log, the test run and the diff stay with the run, so a reviewer sees the job fire and sees which carts the test says it touches. A team with several stores runs the same request across all of them at once, each in its own sandbox.

Frequently asked questions

Will the job run on every instance of the backend?

No. Medusa runs scheduled jobs in the worker process. In local development the default mode is shared, one process doing both, so medusa develop runs it. In production an instance started with workerMode set to server runs no jobs; you need a worker or shared instance, and the pull request says so.

Why go through a workflow for one metadata update?

Because the starter's AGENTS.md puts business logic in src/workflows, and because the next step, an abandoned-cart email, belongs in the same workflow. updateCartsStep from @medusajs/medusa/core-flows already exists, so the workflow is short and the job only decides which carts to pass in.

How do I run the job on demand?

The job's default export needs only the container, which is what a medusa exec script receives too (see src/scripts/seed-demo-products.ts in the starter). A three-line script that imports the job and calls it with container runs it once from the command line. For a quick check in development, set the schedule to * * * * *, watch the log, then set it back.

What if the server is busy at the scheduled minute?

A cron-scheduled job runs when its time arrives; if the event system is busy and the minute passes, Medusa runs it at the next scheduled time rather than late. For work that must run every few hours whatever the load, Medusa's troubleshooting guide suggests an interval schedule instead of a cron expression, and the pull request points at that option.

More Medusa jobs

The same job on other stacks

More jobs like this: Hand off a long task

Keep reading