1 export const metadata = {
2 title: `${pageNumber} Scheduled Jobs`,
3 }
4
5 # {metadata.title}
6
7 In this chapter, you’ll learn about scheduled jobs and how to use them.
8
9 ## What is a Scheduled Job?
10
11 When building your commerce application, you may need to automate tasks and run them repeatedly at a specific schedule. For example, you need to automatically sync products to a third-party service once a day.
12
13 In other commerce platforms, this feature isn't natively supported. Instead, you have to setup a separate application to execute cron jobs, which adds complexity as to how you expose this task to be executed in a cron job, or how you debug it when it's not running within the platform's tooling.
14
15 Medusa removes this overhead by supporting this feature natively with scheduled jobs. A scheduled job is an asynchronous function that the Medusa application runs at the interval you specify during the Medusa application's runtime. Your efforts are only spent on implementing the functionality performed by the job, such as syncing products to an ERP.
16
17 <Note title="Don't use scheduled jobs if" type="error">
18
19 - You want the action to execute at a specified schedule while the Medusa application **isn't** running. Instead, create a [custom CLI script](../custom-cli-scripts/page.mdx) and execute it using the operating system's equivalent of a cron job.
20 - You want to execute the action once when the application loads. Use [loaders](../modules/loaders/page.mdx) or [custom CLI scripts](../custom-cli-scripts/page.mdx#run-custom-script-on-application-startup) instead.
21 - You want to execute the action if an event occurs. Use [subscribers](../events-and-subscribers/page.mdx) instead.
22
23 </Note>
24
25 ---
26
27 ## How to Create a Scheduled Job?
28
29 You create a scheduled job in a TypeScript or JavaScript file under the `src/jobs` directory. The file exports the asynchronous function to run, and the configurations indicating the schedule to run the function.
30
31 For example, create the file `src/jobs/hello-world.ts` with the following content:
32
33 ![Example of scheduled job file in the application's directory structure](https://res.cloudinary.com/dza7lstvk/image/upload/v1732866423/Medusa%20Book/scheduled-job-dir-overview_ediqgm.jpg)
34
35 export const highlights = [
36 ["6", "greetingJob", "The scheduled job function to execute at a specified interval."]
37 ["6", "container", "Receive the Medusa container as a parameter"],
38 ["7", "logger", "Resolve the logger from the container"],
39 ["14", "config", "The scheduled job's configurations."],
40 ["15", "name", "The job's unique name"],
41 ["16", "schedule", "The schedule to run the job on."]
42 ]
43
44 ```ts title="src/jobs/hello-world.ts" highlights={highlights}
45 import { MedusaContainer } from "@medusajs/framework/types"
46 import {
47 ContainerRegistrationKeys,
48 } from "@medusajs/framework/utils"
49
50 export default async function greetingJob(container: MedusaContainer) {
51 const logger = container.resolve(
52 ContainerRegistrationKeys.LOGGER
53 )
54
55 logger.info("Greeting!")
56 }
57
58 export const config = {
59 name: "greeting-every-minute",
60 schedule: "* * * * *",
61 }
62 ```
63
64 You export an asynchronous function that receives the [Medusa container](../medusa-container/page.mdx) as a parameter. In the function, you resolve the [Logger utility](../../debugging-and-testing/logging/page.mdx) from the Medusa container and log a message.
65
66 You also export a `config` object that has the following properties:
67
68 - `name`: A unique name for the job.
69 - `schedule`: A string that holds a [cron expression](https://crontab.guru/) indicating the schedule to run the job.
70
71 This scheduled job executes every minute and logs into the terminal the message `Greeting!`.
72
73 ### Test the Scheduled Job
74
75 To test out your scheduled job, start the Medusa application:
76
77 ```bash npm2yarn
78 npm run dev
79 ```
80
81 After a minute, the following message will be logged to the terminal:
82
83 ```bash
84 info: Greeting!
85 ```
86
87 ### Disable a Scheduled Job
88
89 Do not disable a scheduled job by commenting out or removing the `config` export while keeping the file in `src/jobs/`. This will cause errors when you build or start your Medusa application.
90
91 To disable a scheduled job, move its file out of the `src/jobs` directory. For example, move it to `src/scripts/` or any directory other than `src/jobs/`.
92
93 ### Troubleshooting Scheduled Jobs
94
95 If your scheduled job is not running at the expected times, refer to the [Scheduled Job Troubleshooting Guide](!resources!/troubleshooting/scheduled-job-not-running).
96
97 ---
98
99 ## Example: Sync Products Once a Day
100
101 In a realistic scenario like syncing products to an ERP once a day, you should create a [workflow](../workflows/page.mdx) and execute it in a scheduled job.
102
103 A workflow is a task made up of a series of steps, and you construct it like you would a regular function, but it's a special function that supports rollback mechanism in case of errors, background execution, and more.
104
105 You can learn how to create a workflow in the [Workflows](../workflows/page.mdx) chapter, but this example assumes you already have a `syncProductToErpWorkflow` implemented. To execute this workflow once a day, create a scheduled job at `src/jobs/sync-products.ts` with the following content:
106
107 ```ts title="src/jobs/sync-products.ts"
108 import { MedusaContainer } from "@medusajs/framework/types"
109 import { syncProductToErpWorkflow } from "../workflows/sync-products-to-erp"
110
111 export default async function syncProductsJob(container: MedusaContainer) {
112 await syncProductToErpWorkflow(container)
113 .run()
114 }
115
116 export const config = {
117 name: "sync-products-job",
118 schedule: "0 0 * * *",
119 }
120 ```
121
122 In the scheduled job function, you execute the `syncProductToErpWorkflow` by invoking it and passing it the container, then invoking the `run` method. You also specify in the exported configurations the schedule `0 0 * * *` which indicates midnight time of every day.
123
124 The next time you start the Medusa application, it will run this job every day at midnight.
125
126 ---
127
128 ## Check the Scheduled Time of a Job
129
130 Medusa runs scheduled jobs at the pattern you specify in the `schedule` property of the job's configurations. During a run, you can check the exact date and time the job was scheduled to run at using the `context` parameter of the scheduled job function.
131
132 <Note>
133
134 The `context` parameter is available since Medusa [v2.17.0](https://github.com/medusajs/medusa/releases/tag/v2.17.0).
135
136 </Note>
137
138 For example:
139
140 ```ts title="src/jobs/hello-world.ts"
141 import { MedusaContainer } from "@medusajs/framework/types"
142 import { ScheduledJobContext } from "@medusajs/framework"
143 import {
144 ContainerRegistrationKeys,
145 } from "@medusajs/framework/utils"
146
147 export default async function greetingJob(
148 container: MedusaContainer,
149 context: ScheduledJobContext
150 ) {
151 const logger = container.resolve(
152 ContainerRegistrationKeys.LOGGER
153 )
154
155 logger.info(`Greeting! Scheduled for: ${context.scheduledFor}`)
156 }
157
158 export const config = {
159 name: "greeting-every-minute",
160 schedule: "* * * * *",
161 }
162 ```
163
164 The `context` parameter is an object that has the following property:
165
166 - `scheduledFor`: A `Date` object indicating the exact date and time the job was scheduled to run at.