Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 33 ยท Events and Background Work

Scheduled Jobs

Run recurring tasks in Medusa with scheduled jobs: the jobs folder, cron schedules, numberOfExecutions, what belongs in a job, and worker mode in production.

Some work is not triggered by a customer or an event but by the clock: sync inventory every night, delete abandoned carts every hour, email a sales summary every Monday. Medusa calls these scheduled jobs. A job is a function in a file plus a cron expression saying when it runs.

In this lesson you learn how to write a job, how cron schedules work, how to limit the number of executions, what is worth putting in a job, and why running several server instances needs care. The Medusa code is read-only; the stand-ins implement a cron-field matcher and a small scheduler so cron stops being mysterious.

A job file

A scheduled job lives in src/jobs/. It default-exports an async function that receives the container, and exports a config with a unique name and a schedule. This is real, read-only Medusa code:

TypeScript
// src/jobs/cancel-stale-drafts.ts
import { MedusaContainer } from "@medusajs/framework/types"
import { ContainerRegistrationKeys } from "@medusajs/framework/utils"

export default async function cancelStaleDrafts(container: MedusaContainer) {
  const logger = container.resolve(ContainerRegistrationKeys.LOGGER)
  const query = container.resolve(ContainerRegistrationKeys.QUERY)

  const { data: drafts } = await query.graph({
    entity: "order",
    fields: ["id", "created_at"],
    filters: { status: "draft" },
  })

  logger.info(`Found ${drafts.length} draft orders to review`)
  // Delegate the actual changes to a workflow so they can be rolled back.
}

export const config = {
  name: "cancel-stale-drafts",
  schedule: "0 3 * * *", // every day at 03:00
}

The job receives the same container as routes and subscribers (Architecture: Modules, Workflows and the Container). As with subscribers, keep the job short and call a workflow for any real change, so you get steps, retries and compensation.

Limiting executions

config accepts an optional numberOfExecutions. With a value of 3, the job runs on its next three scheduled times and then stops. It is useful for one-off migrations or time-limited campaigns (for example "run every minute until the campaign data is loaded"). Omit it for a job that should run forever.

Jobs are discovered when the server starts, so a new or changed schedule needs a restart. During development you can also call the exported function yourself, or run it from a script, to test the logic without waiting for the clock.

Reading a cron expression

The schedule is a standard cron expression with five fields:

Text
 minute  hour  day-of-month  month  day-of-week
   0      3         *          *         *      -> every day at 03:00
  */15    *         *          *         *      -> every 15 minutes
   0      9         *          *        1-5     -> 09:00 on weekdays
   30     2         1          *         *      -> 02:30 on the 1st of each month

Each field accepts:

  • * for every value,
  • a number such as 5,
  • a list such as 1,15,
  • a range such as 1-5,
  • a step such as */10 (every 10th value) or 0-30/10.

Day-of-week runs from 0 to 6 starting on Sunday. A cron matcher asks, for a given minute, "does this minute fit all five fields?" The scheduler then checks that question once per minute. The clock a job sees is the server's: set your servers to UTC so "03:00" means the same everywhere, and write down the timezone in a comment next to the schedule.

flowchart LR
    T["Every minute"] --> M{"Matches the<br/>cron fields?"}
    M -- "yes" --> R["Run the job function"]
    M -- "no" --> T
    R --> T

A scheduler is a loop that asks, once per minute, which jobs are due.

What to put in a job

Good fits:

  • Synchronization with an outside system (see Project: Syncing Products with an External System).
  • Cleanup: expired carts, old logs, abandoned draft orders.
  • Reports and digests: a daily sales summary email, a stock-below-threshold alert.
  • Maintenance: refreshing caches or recalculating derived data.

Poor fits: reacting to something a customer just did (use an event subscriber) and anything that must run immediately on request (call a workflow from a route).

Design jobs like subscribers: idempotent and bounded. A job can run twice if it overlaps with a slow previous run or if you have more than one instance. Process data in pages instead of loading everything into memory, and let a job exit quickly when there is nothing to do.

Multiple instances and worker mode

In production you often run more than one Medusa process behind a load balancer. If every process had the same job scheduled, each would run it, and a nightly email would be sent several times. Medusa avoids this with worker mode, set through the MEDUSA_WORKER_MODE environment variable and the workerMode option in medusa-config.ts:

Mode Handles HTTP requests Runs jobs and subscribers
shared (default) Yes Yes
server Yes No
worker No Yes

A common production layout is several server instances plus one or two worker instances that process events and scheduled jobs. Even then, make the job tolerant of a second run, because deploys, restarts and a misconfiguration can overlap runs. The Redis-backed workflow engine and event bus also help coordinate. Deploying Medusa shows this layout in context.

If a job needs to be strictly "only one at a time", use a lock: a database row or a Redis key with an expiry that the job acquires first and releases at the end. Without that guarantee, assume overlap can happen.

Stand-in 1: a cron-field matcher

This stand-in parses the five fields and answers whether a date matches. It supports *, numbers, lists, ranges and steps, which covers almost everything you will write. It is not the library Medusa uses, only a model of the logic.

JS Does this minute match the cron expression?

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Stand-in 2: a scheduler with numberOfExecutions

This stand-in drives a simulated clock minute by minute, runs each due job and stops a job after its numberOfExecutions. A lock flag also shows how to skip a run when the previous one is still going. The time is simulated so the output is deterministic.

JS A scheduler that honors numberOfExecutions and a lock

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The "warmup" job is due every 20 minutes but stops after two runs. The "slow-report" job never unlocks, so its second due time is skipped, which is what a lock does when a previous run has not finished.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the cron expression "*/15 * * * *" mean?

    The first field is minutes, and "*/15" means every 15th minute (0, 15, 30 and 45).
  2. 2. What does numberOfExecutions do in a job's config?

    After the given number of scheduled runs the job no longer executes. Omit it for a job that should run forever.
  3. 3. Why is worker mode useful with several Medusa instances?

    With server and worker modes, jobs run on workers instead of every instance, so a job is not executed once per server.
  4. 4. Which task is the better fit for a scheduled job than for a subscriber?

    Scheduled jobs are driven by the clock. Reactions to something a customer just did belong to events.

Summary

  • A scheduled job is a file in src/jobs/ with a default-exported function and a config holding a unique name and a cron schedule.
  • Cron has five fields (minute, hour, day-of-month, month, day-of-week) with *, lists, ranges and steps; keep servers on UTC.
  • numberOfExecutions stops a job after a fixed number of runs.
  • Jobs should be short, bounded and idempotent, and should delegate changes to workflows.
  • Use server and worker modes in production, and add a lock if a job must never overlap.

Next: Payment Providers